forked from it-sos/golibs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
52 lines (46 loc) · 1.13 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
package http
import (
"bytes"
"io"
"io/ioutil"
"log"
"net/http"
)
// Get 发起get请求
func Get(url string) []byte {
resp, err := http.Get(url)
if err != nil {
log.Panicf("An error occurred while requesting: %v", err)
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Panicf("An error occurred while closing the body: %v", err)
}
}(resp.Body)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Panicf("An error occurred while reading data: %v", err)
}
return body
}
// PostJson 发起post请求
// params, _ := json.Marshal(map[string]string{"name": "Test"})
func PostJson(url string, params []byte) []byte {
responseBody := bytes.NewBuffer(params)
resp, err := http.Post(url, "application/json", responseBody)
if err != nil {
log.Panicf("An error occurred while requesting: %v", err)
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Panicf("An error occurred while closing the body: %v", err)
}
}(resp.Body)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Panicf("An error occurred while reading data: %v", err)
}
return body
}