-
Notifications
You must be signed in to change notification settings - Fork 29
/
http.go
166 lines (136 loc) · 3.89 KB
/
http.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
package smartapigo
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"time"
)
// HTTPClient represents an HTTP client.
type HTTPClient interface {
Do(method, rURL string, params map[string]interface{}, headers http.Header) (HTTPResponse, error)
DoEnvelope(method, url string, params map[string]interface{}, headers http.Header, obj interface{}) error
GetClient() *httpClient
}
// httpClient is the default implementation of HTTPClient.
type httpClient struct {
client *http.Client
hLog *log.Logger
debug bool
}
// HTTPResponse encompasses byte body + the response of an HTTP request.
type HTTPResponse struct {
Body []byte
Response *http.Response
}
type envelope struct {
Status bool `json:"status"`
ErrorCode string `json:"errorcode"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
// NewHTTPClient returns a self-contained HTTP request object
// with underlying keep-alive transport.
func NewHTTPClient(h *http.Client, hLog *log.Logger, debug bool) HTTPClient {
if hLog == nil {
hLog = log.New(os.Stdout, "base.HTTP: ", log.Ldate|log.Ltime|log.Lshortfile)
}
if h == nil {
h = &http.Client{
Timeout: time.Duration(5) * time.Second,
Transport: &http.Transport{
MaxIdleConnsPerHost: 10,
ResponseHeaderTimeout: time.Second * time.Duration(5),
},
}
}
return &httpClient{
hLog: hLog,
client: h,
debug: debug,
}
}
// Do executes an HTTP request and returns the response.
func (h *httpClient) Do(method, rURL string, params map[string]interface{}, headers http.Header) (HTTPResponse, error) {
var (
resp = HTTPResponse{}
postParams io.Reader
err error
)
if method == http.MethodPost && params != nil {
jsonParams, err := json.Marshal(params)
if err != nil {
return resp, err
}
postParams = bytes.NewBuffer(jsonParams)
}
req, err := http.NewRequest(method, rURL, postParams)
if err != nil {
h.hLog.Printf("Request preparation failed: %v", err)
return resp,err
}
if headers != nil {
req.Header = headers
}
// If a content-type isn't set, set the default one.
if req.Header.Get("Content-Type") == "" {
if method == http.MethodPost || method == http.MethodPut {
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
}
}
// If the request method is GET or DELETE, add the params as QueryString.
//if method == http.MethodGet || method == http.MethodDelete {
// req.URL.RawQuery = params.Encode()
//}
r, err := h.client.Do(req)
if err != nil {
h.hLog.Printf("Request failed: %v", err)
return resp,err
}
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
h.hLog.Printf("Unable to read response: %v", err)
return resp,err
}
resp.Response = r
resp.Body = body
if h.debug {
h.hLog.Printf("%s %s -- %d %v", method, req.URL.RequestURI(), resp.Response.StatusCode, req.Header)
}
return resp, nil
}
// DoEnvelope makes an HTTP request and parses the JSON response (fastglue envelop structure)
func (h *httpClient) DoEnvelope(method, url string, params map[string]interface{}, headers http.Header, obj interface{}) error {
resp, err := h.Do(method, url, params, headers)
if err != nil {
return err
}
// Successful request, but error envelope.
if resp.Response.StatusCode >= http.StatusBadRequest {
var e envelope
if err := json.Unmarshal(resp.Body, &e); err != nil {
h.hLog.Printf("Error parsing JSON response: %v", err)
return err
}
return NewError(e.ErrorCode, e.Message, e.Data)
}
// We now unmarshal the body.
envl := envelope{}
envl.Data = obj
if err := json.Unmarshal(resp.Body, &envl); err != nil {
h.hLog.Printf("Error parsing JSON response: %v | %s", err, resp.Body)
return err
}
if !envl.Status {
return NewError(envl.ErrorCode, envl.Message, envl.Data)
}
return nil
}
// GetClient return's the underlying net/http client.
func (h *httpClient) GetClient() *httpClient {
return h
}