This repository has been archived by the owner on Sep 27, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
89 lines (75 loc) · 2.2 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
/**
* Copyright (c) 2018, TransChain.
*
* This source code is licensed under the Apache 2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
package api
import (
"github.com/valyala/fasthttp"
"github.com/katena-chain/sdk-go-client/utils"
)
// Client is a fasthttp.Client wrapper to dialog with a JSON API.
type Client struct {
fastHttpClient *fasthttp.Client
apiUrl string
}
// Client constructor.
func NewClient(apiUrl string) *Client {
return &Client{
fastHttpClient: &fasthttp.Client{},
apiUrl: apiUrl,
}
}
// Get wraps the doRequest method to do a GET HTTP request.
func (c *Client) Get(route string, queryValues map[string]string) (*RawResponse, error) {
return c.doRequest("GET", route, queryValues, nil)
}
// Post wraps the doRequest method to do a POST HTTP request.
func (c *Client) Post(route string, queryValues map[string]string, body []byte) (*RawResponse, error) {
return c.doRequest("POST", route, queryValues, body)
}
// doRequest uses the fasthttp.Client to call a distant api and returns a response.
// The body will be marshaled to JSON.
func (c *Client) doRequest(
method string,
route string,
queryValues map[string]string,
body []byte,
) (*RawResponse, error) {
req := fasthttp.AcquireRequest()
resp := fasthttp.AcquireResponse()
defer func() {
if req != nil {
req.SetConnectionClose()
fasthttp.ReleaseRequest(req)
}
if resp != nil {
resp.SetConnectionClose()
fasthttp.ReleaseResponse(resp)
}
}()
uri, err := utils.GetUri(c.apiUrl, []string{route}, queryValues)
if err != nil {
return nil, err
}
req.SetRequestURI(uri.String())
if body != nil {
req.Header.SetContentType("application/json")
req.SetBody(body)
}
req.Header.SetMethod(method)
err = c.fastHttpClient.Do(req, resp)
if err != nil {
return nil, err
}
return &RawResponse{
StatusCode: resp.StatusCode(),
Body: resp.Body(),
}, nil
}
// Response is a fasthttp.Response wrapper.
type RawResponse struct {
StatusCode int
Body []byte
}