-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
90 lines (73 loc) · 1.88 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
package http
import (
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
)
const HttpReqTimeout = 20 * time.Second
func HttpGet(url string) ([]byte, error) {
resp, err := http.Get(url)
if nil != resp {
defer func() {
err := resp.Body.Close()
if err != nil {
}
}()
}
if nil != err {
return nil, err
}
return ioutil.ReadAll(resp.Body)
}
func HTTPPostForm(reqUrl string, headers map[string]string, payload io.Reader) ([]byte, error) {
if headers == nil {
headers = make(map[string]string)
}
headers["Content-Type"] = "application/x-www-form-urlencoded"
return HTTPRequest("POST", reqUrl, headers, payload)
}
// HTTPPostJSON with json []byte
func HTTPPostJSON(reqUrl string, headers map[string]string, payload io.Reader) ([]byte, error) {
if headers == nil {
headers = make(map[string]string)
}
headers["Content-Type"] = "text/json"
return HTTPRequest("POST", reqUrl, headers, payload)
}
func HTTPRequest(method string, reqUrl string, headers map[string]string, payload io.Reader) ([]byte, error) {
req, err := http.NewRequest(method, reqUrl, payload)
if err != nil {
return nil, errors.New("make http request error: " + err.Error())
}
for k, v := range headers {
req.Header.Add(k, v)
}
/*ctx := req.Context()
nextCtx, _ := context.WithDeadline(ctx, time.Now().Add(HttpReqTimeout))
req.WithContext(nextCtx)*/
client := &http.Client{
Timeout: HttpReqTimeout,
}
resp, err := client.Do(req)
if resp != nil {
defer func() {
err := resp.Body.Close()
if err != nil {
}
}()
}
if err != nil {
return nil, errors.New("do http request error: " + err.Error())
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errors.New("ready http response error: " + err.Error())
}
if resp.StatusCode != 200 {
return body, fmt.Errorf(fmt.Sprintf("HttpStatusCode:%d, Desc:%s", resp.StatusCode, string(body)))
}
return body, nil
}