官网:github.com/levigross/grequests
A Go “clone” of the great and famous Requests library
Go语言的grequests库是一个非常方便的HTTP客户端请求库,具有如下特点:
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")
}