-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
89 lines (67 loc) · 1.71 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package matata
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"time"
)
const (
baseURL = "hakuna.ch/api/v1"
)
type Client struct {
BaseURL string
Tennant string
token string
Client *http.Client
}
// TODO: Is a bit weird, since somethines you get a Full error object with status code and message, and other times you just get a json object with at error attribute containing a string
type errorResponse struct {
HTTPStatus int
Status int `json:"status"`
Message string `json:"message"`
Error string `json:"error"`
}
func NewClient(tennant string, token string) *Client {
if tennant == "" {
log.Fatal("a tennant is required")
}
if token == "" {
log.Fatal("a token is required")
}
return &Client{
BaseURL: "https://" + tennant + "." + baseURL,
Tennant: tennant,
token: token,
Client: &http.Client{
Timeout: time.Minute,
},
}
}
func (c *Client) sendRequest(req *http.Request, v interface{}) error {
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("X-Auth-Token", c.token)
res, err := c.Client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
var errRes errorResponse
if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
if errRes.Message == "" {
return fmt.Errorf(fmt.Sprintf("%d - %s", res.StatusCode, http.StatusText(res.StatusCode)))
}
return errors.New(errRes.Message)
}
return fmt.Errorf("unknown error, status code: %d", res.StatusCode)
}
if res.StatusCode == http.StatusNoContent {
return nil
}
if err = json.NewDecoder(res.Body).Decode(&v); err != nil {
return err
}
return nil
}