forked from badkaktus/gorocket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgorocket.go
98 lines (80 loc) · 1.69 KB
/
gorocket.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
96
97
98
package gorocket
import (
"context"
"encoding/json"
"log"
"net/http"
"time"
)
type Client struct {
baseURL string
userID string
xToken string
apiVersion string
HTTPClient *http.Client
timeout time.Duration
}
// NewClient creates new Facest.io client with given API key
func NewClient(url string) *Client {
return &Client{
//userID: user,
HTTPClient: &http.Client{
Timeout: 5 * time.Minute,
},
//xToken: token,
baseURL: url,
apiVersion: "api/v1",
}
}
// NewClient creates new Facest.io client with given API key
func NewWithOptions(url string, opts ...Option) *Client {
c := &Client{
HTTPClient: &http.Client{
Timeout: 5 * time.Minute,
},
baseURL: url,
apiVersion: "api/v1",
}
for _, o := range opts {
o(c)
}
return c
}
type Option func(*Client)
func WithTimeout(d time.Duration) Option {
return func(c *Client) {
c.timeout = d
}
}
func WithUserID(userID string) Option {
return func(c *Client) {
c.userID = userID
}
}
func WithXToken(xtoken string) Option {
return func(c *Client) {
c.xToken = xtoken
}
}
func (c *Client) sendRequest(req *http.Request, v interface{}) error {
req.Header.Set("Accept", "application/json; charset=utf-8")
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Add("X-Auth-Token", c.xToken)
req.Header.Add("X-User-Id", c.userID)
if c.timeout > 0 {
ctx, cancel := context.WithTimeout(req.Context(), c.timeout)
defer cancel()
req = req.WithContext(ctx)
}
res, err := c.HTTPClient.Do(req)
if err != nil {
log.Println(err)
return err
}
defer res.Body.Close()
resp := v
if err = json.NewDecoder(res.Body).Decode(&resp); err != nil {
return err
}
return nil
}