-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_client.go
84 lines (73 loc) · 1.84 KB
/
http_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
package iptrace
import (
"encoding/json"
"io"
"io/ioutil"
"net/http"
"time"
"github.com/google/go-querystring/query"
)
// HTTPClient -
type HTTPClient interface {
Get(string, interface{}) ([]byte, error)
}
// CLHTTPClient - impelemts HTTPClient interface clear ip default client
type CLHTTPClient struct {
*http.Client
BaseURI string
APIKey string
}
//NewHTTPClient - create the clear ip client with api key
func NewHTTPClient(apiKey string, BaseURI string) CLHTTPClient {
return CLHTTPClient{Client: &http.Client{
Timeout: time.Second * 10,
},
APIKey: apiKey,
BaseURI: BaseURI,
}
}
// Get default http client
func (c CLHTTPClient) Get(url string, queryParams interface{}) ([]byte, error) {
// Setup request
req, _ := http.NewRequest("GET", c.BaseURI+url+"?apikey="+c.APIKey, nil)
req.Header.Add("Accept", "application/json")
if queryParams != nil {
addQueryParams(req, queryParams)
}
// Do request
resp, err := c.Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Read response
data, err := c.readAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode >= 400 {
return nil, c.parseResponseError(data, resp.StatusCode)
}
return data, err
}
func (c CLHTTPClient) parseResponseError(data []byte, statusCode int) HTTPError {
errorList := HTTPErrorList{}
err := json.Unmarshal(data, &errorList)
if err != nil {
return NewUnknownHTTPError(statusCode)
}
if len(errorList.Errors) == 0 {
return NewUnknownHTTPError(statusCode)
}
httpError := errorList.Errors[0]
httpError.StatusCode = statusCode
return httpError // only care about the first
}
func (c CLHTTPClient) readAll(body io.Reader) ([]byte, error) {
b, err := ioutil.ReadAll(body)
return b, err
}
func addQueryParams(req *http.Request, params interface{}) {
v, _ := query.Values(params)
req.URL.RawQuery = v.Encode()
}