-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhttp.go
More file actions
85 lines (80 loc) · 1.82 KB
/
Copy pathhttp.go
File metadata and controls
85 lines (80 loc) · 1.82 KB
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
package goVsysSdk
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"time"
"strconv"
"sync"
)
const defaultTimeOut = 15 * time.Second
var gClient *http.Client
var gClientOnce sync.Once
func getHttpClient() *http.Client{
gClientOnce.Do(func(){
gClient = &http.Client{
Timeout: defaultTimeOut,
}
})
return gClient
}
func (a *VsysApi) httpPost(path string, data interface{}) (body []byte, err error) {
url:=a.nodeAddress +path
client := getHttpClient()
d, err := json.Marshal(data)
if err != nil {
return []byte{}, err
}
resp, err := client.Post(url, "application/json", bytes.NewBuffer(d))
if err != nil {
return []byte{}, err
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return []byte{}, err
}
if err := getErrResp(resp, body); err != nil {
return []byte{}, err
}
return body, nil
}
func (a *VsysApi) httpGet(path string) (body []byte, err error) {
url:=a.nodeAddress +path
httpReq,err:=http.NewRequest("GET",url,nil)
if err!=nil{
return nil,err
}
if a.req.ApiKey!=""{
httpReq.Header.Set("api_key",a.req.ApiKey)
}
client := getHttpClient()
resp, err := client.Do(httpReq)
if err != nil {
return []byte{}, err
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return []byte{}, err
}
err = getErrResp(resp, body)
if err != nil {
return []byte{}, err
}
return body, nil
}
func getErrResp(resp *http.Response, body []byte) (err error) {
if resp.StatusCode != 200 {
errResp := CommonResp{}
err := json.Unmarshal(body, &errResp)
if err != nil {
return errors.New("StatusCodeError ["+strconv.Itoa(int(resp.StatusCode))+"] ["+string(body)+"] "+err.Error())
} else {
return errors.New("hrw6sqkdv6 ["+strconv.Itoa(int(resp.StatusCode))+"] "+errResp.Message+" ["+string(body)+"]")
}
}
return nil
}