Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
121 lines (101 loc) · 2.48 KB
/
Copy pathmain.go
File metadata and controls
121 lines (101 loc) · 2.48 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package main
import (
"context"
"fmt"
"log"
"github.com/Si40Code/kit/httpclient"
"github.com/Si40Code/kit/logger"
)
func main() {
// 初始化 logger
err := logger.Init(
logger.WithLevel(logger.InfoLevel),
logger.WithFormat(logger.ConsoleFormat),
logger.WithStdout(),
)
if err != nil {
log.Fatal(err)
}
defer logger.Sync()
fmt.Println("=== 示例 1: 基本 GET 请求 ===")
example1BasicGet()
fmt.Println("\n=== 示例 2: POST 请求 ===")
example2Post()
fmt.Println("\n=== 示例 3: 带查询参数的请求 ===")
example3QueryParams()
fmt.Println("\n=== 示例 4: 自定义配置 ===")
example4CustomConfig()
}
// 示例 1: 基本 GET 请求
func example1BasicGet() {
// 创建客户端
client := httpclient.New(
httpclient.WithLogger(logger.Default()),
)
// 发起请求
resp, err := client.R(context.Background()).
Get("https://httpbin.org/get")
if err != nil {
log.Printf("请求失败: %v", err)
return
}
fmt.Printf("状态码: %d\n", resp.StatusCode())
fmt.Printf("响应体: %s\n", resp.String())
}
// 示例 2: POST 请求
func example2Post() {
client := httpclient.New(
httpclient.WithLogger(logger.Default()),
)
type User struct {
Name string `json:"name"`
Email string `json:"email"`
}
user := User{
Name: "Alice",
Email: "[email protected]",
}
resp, err := client.R(context.Background()).
SetBody(user).
Post("https://httpbin.org/post")
if err != nil {
log.Printf("请求失败: %v", err)
return
}
fmt.Printf("状态码: %d\n", resp.StatusCode())
fmt.Printf("响应体: %s\n", resp.String())
}
// 示例 3: 带查询参数的请求
func example3QueryParams() {
client := httpclient.New(
httpclient.WithLogger(logger.Default()),
)
resp, err := client.R(context.Background()).
SetQueryParams(map[string]string{
"page": "1",
"pageSize": "10",
}).
Get("https://httpbin.org/get")
if err != nil {
log.Printf("请求失败: %v", err)
return
}
fmt.Printf("状态码: %d\n", resp.StatusCode())
fmt.Printf("响应体: %s\n", resp.String())
}
// 示例 4: 自定义配置
func example4CustomConfig() {
client := httpclient.New(
httpclient.WithLogger(logger.Default()),
httpclient.WithTimeout(10*1000000000), // 10 seconds
httpclient.WithMaxBodyLogSize(1024), // 1KB
)
resp, err := client.R(context.Background()).
SetHeader("User-Agent", "MyApp/1.0").
Get("https://httpbin.org/get")
if err != nil {
log.Printf("请求失败: %v", err)
return
}
fmt.Printf("状态码: %d\n", resp.StatusCode())
}