-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
105 lines (84 loc) · 2.12 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
96
97
98
99
100
101
102
103
104
105
// Copyright (c) 2020 Pieoneers Software Incorporated. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package client
import (
"github.com/pieoneers/jsonapi-go"
"io/ioutil"
"net/http"
"reflect"
)
//Client represents JSON API client and contain configuration values in Config
type Client struct {
httpClient *http.Client
Config Config
}
//NewClient method returns new Client instance
func NewClient(c Config) *Client {
config := NewConfig(c)
client := &Client{
httpClient: &http.Client{
Timeout: config.Timeout,
},
Config: config,
}
return client
}
//Get returns GET ready Request
func (c *Client) Get(path string) (*Request, error) {
req, reqErr := NewRequest("GET", path, nil)
if reqErr != nil {
return nil, reqErr
}
return req, nil
}
//Head returns HEAD ready Request
func (c *Client) Head(path string) (*Request, error) {
req, reqErr := NewRequest("HEAD", path, nil)
if reqErr != nil {
return nil, reqErr
}
return req, nil
}
//Post returns POST ready Request
func (c *Client) Post(path string, in interface{}) (*Request, error) {
req, reqErr := NewRequest("POST", path, in)
if reqErr != nil {
return nil, reqErr
}
return req, nil
}
//Do proceeds the provided Request
func (c *Client) Do(req *Request, out interface{}) (*Response, error) {
baseURL := c.Config.BaseURL
httpClient := c.httpClient
httpReq, reqErr := http.NewRequest(req.Method, baseURL+req.RequestURI(), req.Body)
if reqErr != nil {
return nil, reqErr
}
httpReq.Header = req.Header
httpRes, resErr := httpClient.Do(httpReq)
if resErr != nil {
return nil, resErr
}
res := Response{
Response: http.Response{
StatusCode: httpRes.StatusCode,
Header: httpRes.Header,
Body: httpRes.Body,
Request: httpRes.Request,
},
}
payload, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
return nil, readErr
}
if len(payload) > 0 && reflect.TypeOf(out) != nil {
document, unmarshalErr := jsonapi.Unmarshal(payload, out)
if unmarshalErr != nil {
return nil, unmarshalErr
}
res.Document = document
}
return &res, nil
}