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

什么是grequests

官网:github.com/levigross/grequests

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

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

使用

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")
	}
10-08 02:07