-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
66 lines (49 loc) · 1.14 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
package utils
import (
"crypto/tls"
"io"
"io/ioutil"
"log"
"net/http"
"time"
jsoniter "github.com/json-iterator/go"
)
var json = jsoniter.ConfigCompatibleWithStandardLibrary
type setRequest func(*http.Request)
func DoHTTP(client *http.Client, method string, setFunc setRequest, body io.Reader, url string, obj interface{}) error {
request, err := http.NewRequest(method, url, body)
if err != nil {
return err
}
if setFunc != nil {
setFunc(request)
}
if client == nil {
tr := &http.Transport{ //x509: certificate signed by unknown authority
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client = &http.Client{Transport: tr, Timeout: 15 * time.Second}
}
resp, err := client.Do(request)
if err != nil {
return err
}
defer resp.Body.Close()
defer client.CloseIdleConnections()
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("read body failed:%s", err)
return err
}
if obj != nil {
if s, ok := obj.(*string); ok {
*s = string(buf)
} else {
if err := json.Unmarshal(buf, obj); err != nil {
log.Printf("unmarshal failed:%s", err)
return err
}
}
}
return nil
}