【go】gorequest包的使用-post/get等用法

背景

在日常工作中经常需要写一写小工具,比如发送get请求,post请求等,在用python时request包比较方便,在用go时可以使用gorequest包,借鉴了py的request包

使用样例

GET请求-client

func getRequest(params map[string]string) (string, error) {
request := gorequest.New()
response, body, errs := request.Get("http://127.0.0.1:8866/get").
//携带参数
Param("username", params["username"]).
Param("password", params["password"]).
End()
if errs != nil {
fmt.Println(errs)
return "", errs[0]
}
if response.StatusCode != 200 {
fmt.Println("服务端返回状态码非200,状态码:", response.StatusCode)
return body, nil
}
return body, nil
}

POST请求-client (form表单)

// 发起post form请求
func postRequestForm(url string, data map[string]any) (string, error) {
request := gorequest.New()
response, body, errs := request.Post(url).
// 设置请求头
Set("Content-Type", "application/x-www-form-urlencoded").
SendMap(data).
End()
if len(errs) > 0 {
fmt.Println(errs)
return "", errs[0]
}
fmt.Println(response.StatusCode)
fmt.Println(body)
if response.StatusCode != 200 {
fmt.Println("服务端返回状态码非200,状态码:", response.StatusCode)
return body, nil
}
return body, nil
}

POST请求-client (传输json格式)

// 发送json请求到服务端
func postRequestJson(url, json string) error {
if len(url) == 0 {
return errors.New("url为空")
}
if len(json) == 0 {
return errors.New("json数据不能为空")
}
if !isJson(json) {
return errors.New("当前行文本不是json格式,跳过")
}
request := gorequest.New()
response, body, errs := request.Post(url).
// 设置请求头
Set("Content-Type", "application/json").
SendString(json).
End()
if len(errs) > 0 {
fmt.Println(errs)
return errs[0]
}
fmt.Println(response.StatusCode)
fmt.Println(body)
if response.StatusCode != 200 {
fmt.Println("服务端返回状态码非200,状态码:", response.StatusCode)
return body, nil
}
return nil
}
// 判断文本是否为json格式
func isJson(str string) bool {
var js map[string]any
return json.Unmarshal([]byte(str), &js) == nil
}

POST请求-client (上传文件)

// 发送文件
func postRequestFile() (string, error){
f, _ := filepath.Abs("/etc/hosts")
bytesOfFile, _ := ioutil.ReadFile(f)
request := gorequest.New()
response, body, errors := request.Post("http://127.0.0.1:5000/file").
Type("multipart").
// 发送文件
SendFile("./abc.txt").
SendFile(bytesOfFile, "hosts", "file").
End()
if errors != nil {
fmt.Println(errs)
return "", errs[0]
}
fmt.Println(response.StatusCode)
fmt.Println(body)
if response.StatusCode != 200 {
fmt.Println("服务端返回状态码非200,状态码:", response.StatusCode)
return body, nil
}
}
posted @   alisleepy  阅读(45)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示