-
Notifications
You must be signed in to change notification settings - Fork 18
/
client.go
83 lines (62 loc) · 1.6 KB
/
client.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
package main
import (
"fmt"
"github.com/valyala/fasthttp"
)
func main() {
getRes()
postRes()
}
// 简单的get请求
func getRes() {
url := `http://httpbin.org/get`
status, resp, err := fasthttp.Get(nil, url)
if err != nil {
fmt.Println("请求失败:", err.Error())
return
}
if status != fasthttp.StatusOK {
fmt.Println("请求没有成功:", status)
return
}
fmt.Println(string(resp))
}
// 简单的post请求
func postRes() {
url := `http://httpbin.org/post?key=123`
// 填充表单,类似于net/url
args := &fasthttp.Args{}
args.Add("name", "test")
args.Add("age", "18")
status, resp, err := fasthttp.Post(nil, url, args)
if err != nil {
fmt.Println("请求失败:", err.Error())
return
}
if status != fasthttp.StatusOK {
fmt.Println("请求没有成功:", status)
return
}
fmt.Println(string(resp))
}
// 在有性能要求的代码中,通过 AcquireRequest 和 AcquireResponse 来获取 req 和 resp
func customizedReq() {
url := `http://httpbin.org/post?key=123`
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req) // 用完需要释放资源
req.SetRequestURI(url)
requestBody := []byte(`{"request":"test"}`)
req.SetBody(requestBody)
// 默认是application/x-www-form-urlencoded
req.Header.SetContentType("application/json")
req.Header.SetMethod("POST")
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp) // 用完需要释放资源
client := &fasthttp.Client{}
if err := client.Do(req, resp); err != nil {
fmt.Println("请求失败:", err.Error())
return
}
b := resp.Body()
fmt.Println("result:\r\n", string(b))
}