-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhttp_request.go
65 lines (53 loc) · 1.47 KB
/
http_request.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
package biteship
import (
"encoding/json"
"io"
"io/ioutil"
"net/http"
)
type HttpRequest interface {
Call(method string, url string, secretKey string, body io.Reader, result interface{}) *Error
}
type HttpRequestImpl struct {
Config *ConfigOption
}
func (client *HttpRequestImpl) Call(method string, url string, secretKey string, body io.Reader, result interface{}) *Error {
if secretKey == "" {
return &Error{
Status: http.StatusUnauthorized,
Message: "missing/invalid secret key",
}
}
req, errNewReq := http.NewRequest(method, url, body)
if errNewReq != nil {
return &Error{
Status: http.StatusInternalServerError,
Message: "Cannot create request",
RawError: errNewReq.Error(),
}
}
req.Header.Add("Authorization", secretKey)
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
return client.doRequest(req, result)
}
func (client *HttpRequestImpl) doRequest(req *http.Request, result interface{}) *Error {
httpClient := &http.Client{}
response, errRequest := httpClient.Do(req)
if errRequest != nil {
return ErrorGo(errRequest)
}
defer response.Body.Close()
respBody, errRead := ioutil.ReadAll(response.Body)
if errRead != nil {
return ErrorGo(errRead)
}
if response.StatusCode < 200 || response.StatusCode > 299 {
return ErrorHttp(response.StatusCode, respBody)
}
errUnmarshall := json.Unmarshal(respBody, &result)
if errUnmarshall != nil {
return ErrorGo(errUnmarshall)
}
return nil
}