文章目录

golang常用库之-HTTP客户端请求库 grequests什么是grequests使用

golang常用库之-HTTP客户端请求库 grequests

什么是grequests

官网:github.com/levigross/grequests

A Go “clone” of the great and famous Requests library

Go语言的grequests库是一个非常方便的HTTP客户端请求库,具有如下特点:

使用简单,与Python的requests库类似,可以通过Get/Post/Put等方法发起请求。支持设置请求参数,包括query参数、headers、cookies等。支持添加代理,实现代理请求。支持HTTPS请求。支持文件上传。支持超时控制。支持连接池,重用连接。支持自动编码请求参数为表单格式。返回支持直接读取响应体或绑定为JSON。同时支持同步和异步请求。跨平台,支持Linux、Mac、Windows等。社区活跃,持续维护更新。

使用

get请求

resp, err := grequests.Get("http://httpbin.org/get", nil)

// You can modify the request by passing an optional RequestOptions struct

if err != nil {

log.Fatalln("Unable to make request: ", err)

}

fmt.Println(resp.String())

post 请求demo,来自开源项目elkeid:internal/agent_center/httptrans/client/config.go

func GetConfigFromRemote(agentID string, detail map[string]interface{}) ([]*pb.ConfigItem, error) {

rOption := &grequests.RequestOptions{

JSON: detail,

}

resp, err := grequests.Post(fmt.Sprintf(ConfigUrl, common.GetRandomManageAddr()), rOption)

if err != nil {

ylog.Errorf("GetConfigFromRemote", "error %s %s", agentID, err.Error())

return nil, err

}

if !resp.Ok {

ylog.Errorf("GetConfigFromRemote", "response code is not 200, AgentID: %s, StatusCode: %d,String: %s", agentID, resp.StatusCode, resp.String())

return nil, errors.New("status code is not ok")

}

var response ResAgentConf

err = json.Unmarshal(resp.Bytes(), &response)

if err != nil {

ylog.Errorf("GetConfigFromRemote", "agentID: %s, error: %s, resp:%s", agentID, err.Error(), resp.String())

return nil, err

}

if response.Code != 0 {

ylog.Errorf("GetConfigFromRemote", "response code is not 0, agentID: %s, resp: %s", agentID, resp.String())

return nil, errors.New("response code is not 0")

}

好文阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: