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


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

    什么是grequests

    官网:github.com/levigross/grequests

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

    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())
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    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")
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
  • 相关阅读:
    力扣 -- 647. 回文子串
    如何获取IP归属地
    Sealos 新功能“定时任务”上线(省钱大杀器)
    【C++】模板特化、模板分离编译
    什么是客户体验自动化?
    MyBatis使⽤PageHelper(MySQL)
    【测开求职】面试题:Redis 吐血整理
    C#数组介绍
    Xshell连接Docker版本CentOS7
    【网络】网络基础知识详解
  • 原文地址:https://blog.csdn.net/inthat/article/details/133616429