-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
99 lines (84 loc) · 2.16 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
package shopeepay
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"time"
)
type Client struct {
APIEnvType Env
APIEnvRegion EnvRegion
ClientID string
ClientSecret string
MerchantExtID string
StoreExtID string
LogLevel int
Logger *log.Logger
}
func NewClient() Client {
return Client{
APIEnvType: Sandbox,
APIEnvRegion: ID,
LogLevel: 2,
Logger: log.New(os.Stderr, "", log.LstdFlags),
}
}
var defHTTPTimeout = 80 * time.Second
var httpClient = &http.Client{Timeout: defHTTPTimeout}
func (c *Client) DoRequest(method, path string, body interface{}, v interface{}) error {
byteJson, _ := json.Marshal(body)
logLevel := c.LogLevel
logger := c.Logger
req, err := http.NewRequest(method, path, bytes.NewBuffer(byteJson))
if err != nil {
if logLevel > 0 {
logger.Println("Request creation failed: ", err)
}
return err
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("X-Airpay-ClientId", c.ClientID)
req.Header.Add("X-Airpay-Req-H", CreateSignatureHeaders(byteJson, c.ClientSecret))
start := time.Now()
if logLevel > 1 {
logger.Println("Request ", req.Method, ": ", req.URL.Host, req.URL.Path)
}
// Set Log Request
RequestLog := RequestLog{
Method: req.Method,
Host: req.URL.Host,
Path: req.URL.Path,
RequestBody: Stringify(body),
}
logger.Println(Stringify(RequestLog))
res, err := httpClient.Do(req)
if err != nil {
logger.Println("Cannot send request : ", err)
return err
}
// Println stdout for checking request body and response
logger.Println("Completed in ", time.Since(start))
defer res.Body.Close()
if res.StatusCode != 200 {
errMessage := fmt.Sprintf("Cannot send request and get status code %d from shopeepay", res.StatusCode)
return errors.New(errMessage)
}
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
logger.Println("Cannot read response body: ", err)
return err
}
if v != nil {
response := json.Unmarshal(resBody, v)
RequestLog.ResponseBody = Stringify(v)
RequestLog.TimeLength = int(time.Since(start))
logger.Println(Stringify(RequestLog))
return response
}
return nil
}