-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
93 lines (85 loc) · 1.97 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
package xenditfasthttp
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"os"
"time"
"github.com/valyala/fasthttp"
)
// Client is ...
type Client struct {
Host string
SecretKey string
LogLevel int
Logger *log.Logger
}
var (
defHTTPTimeout = 15 * time.Second
)
// NewClient is ...
func NewClient() Client {
return Client{
LogLevel: 2,
Logger: log.New(os.Stderr, "", log.LstdFlags),
}
}
// NewRequest test is ...
func (c *Client) NewRequest(method, fullPath string, headers map[string]string, body io.Reader) (*fasthttp.Request, error) {
req := fasthttp.AcquireRequest()
req.SetRequestURI(fullPath)
req.Header.SetMethod(method)
if method == fasthttp.MethodPost {
buf := new(bytes.Buffer)
buf.ReadFrom(body)
req.SetBody(buf.Bytes())
}
if headers != nil {
for k, vv := range headers {
req.Header.Set(k, vv)
}
}
return req, nil
}
// ExecuteRequest is ...
func (c *Client) ExecuteRequest(req *fasthttp.Request, v interface{}) error {
logLevel := c.LogLevel
logger := c.Logger
if logLevel > 1 {
logger.Printf("Request %s:%s%s", string(req.Header.Method()), string(req.Host()), string(req.URI().Path()))
}
start := time.Now()
resp := fasthttp.AcquireResponse()
httpClient := &fasthttp.Client{}
err := httpClient.Do(req, resp)
if err != nil {
if logLevel > 0 {
logger.Println("Cannot send request: ", err)
}
return err
}
if logLevel > 2 {
logger.Println("Completed in ", time.Since(start))
}
if v != nil && resp.StatusCode() == 200 {
if err = json.Unmarshal(resp.Body(), v); err != nil {
return err
}
return nil
}
var respErr ResponseError
if err = json.Unmarshal(resp.Body(), &respErr); err != nil {
return err
}
return fmt.Errorf("%s-%s", respErr.ErrorCode, respErr.Message)
}
// Call is ...
func (c *Client) Call(method, path string, header map[string]string, body io.Reader, v interface{}) error {
req, err := c.NewRequest(method, path, header, body)
if err != nil {
return err
}
return c.ExecuteRequest(req, v)
}