-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp-helper.go
61 lines (51 loc) · 1.38 KB
/
http-helper.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
package u_push
import (
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
)
// HTTPPostJSON with json []byte
func httpPostJSON(reqUrl string, headers map[string]string, payload io.Reader, reqTimeout time.Duration) ([]byte, error) {
if headers == nil {
headers = make(map[string]string)
}
headers["Content-Type"] = "text/json"
return httpRequest("POST", reqUrl, headers, payload, reqTimeout)
}
func httpRequest(method string, reqUrl string, headers map[string]string, payload io.Reader, reqTimeout time.Duration) ([]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: reqTimeout,
}
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
}