-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.go
55 lines (49 loc) · 1.19 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
package nap
import (
"bytes"
"encoding/json"
"net/http"
"strings"
)
type Client struct {
Client *http.Client
AuthInfo Authentication
}
func NewClient() *Client {
return &Client{
Client: http.DefaultClient,
}
}
func (c *Client) SetAuth(auth Authentication) {
c.AuthInfo = auth
}
func (c *Client) ProcessRequest(baseURL string, res *RestResource, params map[string]string, payload interface{}) error {
endpoint := strings.TrimLeft(res.RenderEndpoint(params), "/")
trimmedBaseURL := strings.TrimRight(baseURL, "/")
url := trimmedBaseURL + "/" + endpoint
req := buildClientRequest(res.Method, url, payload)
if c.AuthInfo != nil {
req.Header.Add("Authorization", c.AuthInfo.AuthorizationHeader())
}
resp, err := c.Client.Do(req)
if err != nil {
return err
}
return res.Router.CallFunc(resp)
}
func buildClientRequest(method, url string, payload interface{}) *http.Request {
if payload != nil {
payloadBytes, err := json.Marshal(payload)
if err != nil {
return nil
}
payloadBuffer := bytes.NewBuffer(payloadBytes)
req, err := http.NewRequest(method, url, payloadBuffer)
return req
}
req, err := http.NewRequest(method, url, nil)
if err != nil {
return nil
}
return req
}