-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
95 lines (74 loc) · 1.6 KB
/
client.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
90
91
92
93
94
95
package lolo
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
)
type Client struct {
apiKey string
baseUrl string
HttpClient *http.Client
}
func NewClient(apiKey string) (*Client, error) {
baseUrl := os.Getenv("LO_API")
if baseUrl == "" {
baseUrl = "https://dev.lolo.company/api"
}
return &Client{
apiKey: apiKey,
baseUrl: baseUrl,
HttpClient: http.DefaultClient,
}, nil
}
func (client *Client) sendRequest(m, p string, b, out interface{}) error {
req, err := client.createRequest(m, p, b)
if err != nil {
return err
}
var resp *http.Response
resp, err = client.HttpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return fmt.Errorf("API error %s: %s", resp.Status, body)
}
if len(body) == 0 {
body = []byte{'{', '}'}
}
if out == nil {
return nil
}
return json.Unmarshal(body, &out)
}
func (client *Client) buildUrl(p string) string {
return client.baseUrl + p
}
func (client *Client) createRequest(m, p string, b interface{}) (*http.Request, error) {
var bReader io.Reader
if m != "GET" && b != nil {
bJson, err := json.Marshal(b)
if err != nil {
return nil, err
}
fmt.Println("Request body:", string(bJson))
bReader = bytes.NewReader(bJson)
}
url := client.buildUrl(p)
req, err := http.NewRequest(m, url, bReader)
if err != nil {
return nil, err
}
req.Header.Set("LO-API-KEY", client.apiKey)
req.Header.Add("Content-Type", "application/json")
return req, nil
}