forked from veritrans/go-midtrans
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
197 lines (161 loc) · 4.21 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package midtrans
import (
"encoding/json"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"reflect"
"strconv"
"time"
)
var (
defaultHTTPTimeout = 80 * time.Second
defaultHTTPClient = &http.Client{Timeout: defaultHTTPTimeout}
)
// Client struct
type Client struct {
APIEnvType EnvironmentType
ClientKey string
ServerKey string
LogLevel int
Logger *log.Logger
HTTPClient *http.Client
}
type ClientOption func(*Client)
func WithEnvType(envType EnvironmentType) ClientOption {
return func(c *Client) {
c.APIEnvType = envType
}
}
func WithClientKey(key string) ClientOption {
return func(c *Client) {
c.ClientKey = key
}
}
func WithServerKey(key string) ClientOption {
return func(c *Client) {
c.ServerKey = key
}
}
func WithLogLevel(level int) ClientOption {
return func(c *Client) {
c.LogLevel = level
}
}
func WithLogger(logger *log.Logger) ClientOption {
return func(c *Client) {
c.Logger = logger
}
}
func WithHTTPClient(hc *http.Client) ClientOption {
return func(c *Client) {
c.HTTPClient = hc
}
}
// NewClient : this function will always be called when the library is in use
func NewClient(opts ...ClientOption) Client {
client := Client{
APIEnvType: Sandbox,
// LogLevel is the logging level used by the Midtrans library
// 0: No logging
// 1: Errors only
// 2: Errors + informational (default)
// 3: Errors + informational + debug
LogLevel: 2,
Logger: log.New(os.Stderr, "", log.LstdFlags),
HTTPClient: defaultHTTPClient,
}
for _, apply := range opts {
apply(&client)
}
return client
}
// NewRequest : send new request
func (c *Client) NewRequest(method string, fullPath string, body io.Reader) (*http.Request, error) {
logLevel := c.LogLevel
logger := c.Logger
req, err := http.NewRequest(method, fullPath, body)
if err != nil {
if logLevel > 0 {
logger.Println("Request creation failed: ", err)
}
return nil, err
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
req.SetBasicAuth(c.ServerKey, "")
return req, nil
}
// ExecuteRequest : execute request
func (c *Client) ExecuteRequest(req *http.Request, v interface{}) error {
logLevel := c.LogLevel
logger := c.Logger
if logLevel > 1 {
logger.Println("Request ", req.Method, ": ", req.URL.Host, req.URL.Path)
}
start := time.Now()
res, err := c.HTTPClient.Do(req)
if err != nil {
if logLevel > 0 {
logger.Println("Cannot send request: ", err)
}
return err
}
defer res.Body.Close()
if logLevel > 2 {
logger.Println("Completed in ", time.Since(start))
}
if err != nil {
if logLevel > 0 {
logger.Println("Request failed: ", err)
}
return err
}
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
if logLevel > 0 {
logger.Println("Cannot read response body: ", err)
}
return err
}
if logLevel > 2 {
logger.Println("Midtrans response: ", string(resBody))
}
if v != nil {
if err = json.Unmarshal(resBody, v); err != nil {
return err
}
// when return unexpected error, midtrans not return `status_message` but `message`, so this to catch it
error := make(map[string]string)
if res.StatusCode >= 500 {
err := json.Unmarshal(resBody, &error)
if err != nil {
return err
}
}
// we're safe to reflect status_code if response not return status code
if reflect.ValueOf(v).Elem().Kind() == reflect.Struct {
if reflect.ValueOf(v).Elem().FieldByName("StatusCode").Len() == 0 {
reflect.ValueOf(v).Elem().FieldByName("StatusCode").SetString(strconv.Itoa(res.StatusCode))
// response of snap transaction not return StatusMessage
if req.URL.Path != "/snap/v1/transactions" {
reflect.ValueOf(v).Elem().FieldByName("StatusMessage").SetString(error["message"])
}
}
}
}
return nil
}
// Call the Midtrans API at specific `path` using the specified HTTP `method`. The result will be
// given to `v` if there is no error. If any error occurred, the return of this function is the error
// itself, otherwise nil.
func (c *Client) Call(method, path string, body io.Reader, v interface{}) error {
req, err := c.NewRequest(method, path, body)
if err != nil {
return err
}
return c.ExecuteRequest(req, v)
}
// ===================== END HTTP CLIENT ================================================