-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
92 lines (81 loc) · 2.03 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
91
92
/*
* NeoDB
*
* Copyright 2018 The Radon Authors.
* Copyright 2021-2030 The NeoDB Authors.
* Code is licensed under the GPLv3.
*
*/
package xbase
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
)
// makeSimpleRequest used to make a simple http request.
func makeSimpleRequest(ctx context.Context, method string, url string, payload interface{}) (*http.Request, error) {
var data string
if payload != nil {
b, err := json.Marshal(payload)
if err != nil {
return nil, err
}
data = fmt.Sprintf("%s", b)
}
req, err := http.NewRequest(method, url, strings.NewReader(data))
if err != nil {
return nil, err
}
//r.Header.Set("Accept-Encoding", "gzip")
if payload != nil {
req.Header.Set("Content-Type", "application/json")
}
req = req.WithContext(ctx)
return req, nil
}
func httpDo(method string, url string, payload interface{}) (*http.Response, func(), error) {
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
req, err := makeSimpleRequest(ctx, method, url, payload)
if err != nil {
return nil, nil, err
}
client := &http.Client{}
resp, err := client.Do(req)
return resp, func() {
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
}, err
}
// HTTPPost used to do restful post request.
func HTTPPost(url string, payload interface{}) (*http.Response, func(), error) {
return httpDo("POST", url, payload)
}
// HTTPPut used to do restful put request.
func HTTPPut(url string, payload interface{}) (*http.Response, func(), error) {
return httpDo("PUT", url, payload)
}
// HTTPGet used to do restful get request.
func HTTPGet(url string) (string, error) {
resp, cleanup, err := httpDo("GET", url, nil)
if err != nil {
return "", err
}
defer cleanup()
return HTTPReadBody(resp), nil
}
// HTTPReadBody returns the body of the response.
func HTTPReadBody(resp *http.Response) string {
if resp != nil && resp.Body != nil {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err.Error()
}
return string(bodyBytes)
}
return ""
}