python 做办公网站,北京网站设计必看刻,2022年互联网公司排名,wordpress 站内搜索 慢文章目录 Go 语言封装 HTTP 请求的 Curl 工具包#x1f3d7;️ 工具包结构简介核心结构体定义初始化函数 #x1f31f; 功能实现1. 设置请求头2. 构建请求3. 发送请求4. 发送 GET 请求5. 发送 POST 请求6. 发送 PUT 请求7. 发送 DELETE 请求8. 读取响应体 #x1f4a1; 实现… 文章目录 Go 语言封装 HTTP 请求的 Curl 工具包️ 工具包结构简介核心结构体定义初始化函数 功能实现1. 设置请求头2. 构建请求3. 发送请求4. 发送 GET 请求5. 发送 POST 请求6. 发送 PUT 请求7. 发送 DELETE 请求8. 读取响应体 实现思路 示例 总结 Go 语言封装 HTTP 请求的 Curl 工具包
在 Go 语言开发中与 HTTP 服务进行交互是非常常见的需求。本文将分享一个用 Go 语言封装的 Curl 工具包它提供了简洁易用的接口来进行 HTTP 请求包括 GET、POST、PUT 和 DELETE 等常见操作。通过这个工具包可以轻松管理 HTTP 请求头、查询参数和请求体并处理响应。 ️ 工具包结构简介
在这个 curl 工具包中主要定义了一个 Curl 结构体封装了 HTTP 客户端的常见操作。
核心结构体定义
type Curl struct {client *http.Client // http clientbaseURL string // base urlheaders map[string]string // headers
}client使用 http.Client 发送 HTTP 请求。baseURL基础 URL便于在请求时自动拼接路径。headers一个存储 HTTP 请求头的 map支持动态设置。
初始化函数
func NewCurl(baseURL string, timeout time.Duration) *Curl {return Curl{client: http.Client{Timeout: timeout,},baseURL: strings.TrimSuffix(baseURL, /),headers: make(map[string]string),}
}baseURL传入基础 URL。timeout设置超时时间。 功能实现
1. 设置请求头
SetHeader 用于设置 HTTP 请求头
func (c *Curl) SetHeader(key, value string) {c.headers[key] value
}可以通过如下方式动态设置请求头
curl.SetHeader(Content-Type, application/json)2. 构建请求
func (c *Curl) buildRequest(ctx context.Context, method, urlPath string, queryParams map[string]string, body io.Reader) (*http.Request, error) {// 处理完整的 URLfullURL : c.baseURL urlPathif queryParams ! nil {query : url.Values{}for key, value : range queryParams {query.Add(key, value)}fullURL ? query.Encode()}// 创建请求req, err : http.NewRequestWithContext(ctx, method, fullURL, body)if err ! nil {return nil, err}// 设置请求头for key, value : range c.headers {req.Header.Set(key, value)}return req, nil
}3. 发送请求
func (c *Curl) doRequest(req *http.Request) (*http.Response, error) {resp, err : c.client.Do(req)if err ! nil {return nil, err}return resp, nil
}4. 发送 GET 请求
Get 方法通过 HTTP GET 请求获取资源
func (c *Curl) Get(ctx context.Context, urlPath string, queryParams map[string]string) (*http.Response, error) {req, err : c.buildRequest(ctx, http.MethodGet, urlPath, queryParams, nil)if err ! nil {return nil, err}return c.doRequest(req)
}示例
response, err : curl.Get(context.TODO(), /user, map[string]string{id: 123})5. 发送 POST 请求
Post 方法通过 HTTP POST 请求提交数据
func (c *Curl) Post(ctx context.Context, urlPath string, body []byte) (*http.Response, error) {req, err : c.buildRequest(ctx, http.MethodPost, urlPath, nil, bytes.NewBuffer(body))if err ! nil {return nil, err}return c.doRequest(req)
}示例
data : []byte({name:Alice})
response, err : curl.Post(context.TODO(), /user, data)6. 发送 PUT 请求
Put 方法通过 HTTP PUT 请求更新资源
func (c *Curl) Put(ctx context.Context, urlPath string, body []byte) (*http.Response, error) {req, err : c.buildRequest(ctx, http.MethodPut, urlPath, nil, bytes.NewBuffer(body))if err ! nil {return nil, err}return c.doRequest(req)
}示例
data : []byte({age:30})
response, err : curl.Put(context.TODO(), /user, data)7. 发送 DELETE 请求
Delete 方法通过 HTTP DELETE 请求删除资源
func (c *Curl) Delete(ctx context.Context, urlPath string) (*http.Response, error) {req, err : c.buildRequest(ctx, http.MethodDelete, urlPath, nil, nil)if err ! nil {return nil, err}return c.doRequest(req)
}示例
response, err : curl.Delete(context.TODO(), /user)8. 读取响应体
ReadResponseBody 读取 HTTP 响应体并返回字节数组
func ReadResponseBody(resp *http.Response) ([]byte, error) {defer func(Body io.ReadCloser) {err : Body.Close()if err ! nil {fmt.Printf(close response body failed: %v\n, err)}}(resp.Body)return io.ReadAll(resp.Body)
}示例
body, err : ReadResponseBody(response)
if err ! nil {fmt.Println(Read response body error:, err)
} else {fmt.Println(Response body:, string(body))
}实现思路
使用 http.NewRequestWithContext 构建 HTTP 请求对象。通过 client.Do(req) 发送请求。动态设置请求头支持不同的 Content-Type。处理查询参数方便 GET 请求传参。读取响应体处理服务器返回的数据。 示例
完整示例
curl : NewCurl(https://example.com, 10*time.Second)
curl.SetHeader(Authorization, Bearer token)
resp, err : curl.Get(context.TODO(), /api/resource, map[string]string{key: value})
if err ! nil {log.Fatalf(Failed to send GET request: %v, err)
}body, err : ReadResponseBody(resp)
if err ! nil {log.Fatalf(Failed to read response: %v, err)
}fmt.Println(Response:, string(body))总结
通过封装 Curl 结构体简化了 Go 语言中与 HTTP 服务的交互过程提供了灵活的配置和扩展能力。通过这种封装可以快速集成 HTTP 请求减少模板代码的编写提升开发效率。 文章转载自: http://www.morning.bwttp.cn.gov.cn.bwttp.cn http://www.morning.qwbht.cn.gov.cn.qwbht.cn http://www.morning.nfmlt.cn.gov.cn.nfmlt.cn http://www.morning.bpwfr.cn.gov.cn.bpwfr.cn http://www.morning.ghslr.cn.gov.cn.ghslr.cn http://www.morning.dzgyr.cn.gov.cn.dzgyr.cn http://www.morning.stlgg.cn.gov.cn.stlgg.cn http://www.morning.rmxgk.cn.gov.cn.rmxgk.cn http://www.morning.dwwlg.cn.gov.cn.dwwlg.cn http://www.morning.gmmyn.cn.gov.cn.gmmyn.cn http://www.morning.qbtj.cn.gov.cn.qbtj.cn http://www.morning.qjldz.cn.gov.cn.qjldz.cn http://www.morning.zkdmk.cn.gov.cn.zkdmk.cn http://www.morning.xbmwm.cn.gov.cn.xbmwm.cn http://www.morning.txfxy.cn.gov.cn.txfxy.cn http://www.morning.bxrqf.cn.gov.cn.bxrqf.cn http://www.morning.ykbgs.cn.gov.cn.ykbgs.cn http://www.morning.hlkxb.cn.gov.cn.hlkxb.cn http://www.morning.krywy.cn.gov.cn.krywy.cn http://www.morning.bwkhp.cn.gov.cn.bwkhp.cn http://www.morning.dmwbs.cn.gov.cn.dmwbs.cn http://www.morning.rcqyk.cn.gov.cn.rcqyk.cn http://www.morning.rmxgk.cn.gov.cn.rmxgk.cn http://www.morning.czgtt.cn.gov.cn.czgtt.cn http://www.morning.fzwf.cn.gov.cn.fzwf.cn http://www.morning.hnrls.cn.gov.cn.hnrls.cn http://www.morning.mxlmn.cn.gov.cn.mxlmn.cn http://www.morning.jxfsm.cn.gov.cn.jxfsm.cn http://www.morning.qwzpd.cn.gov.cn.qwzpd.cn http://www.morning.wjhpg.cn.gov.cn.wjhpg.cn http://www.morning.xkgyh.cn.gov.cn.xkgyh.cn http://www.morning.bhdyr.cn.gov.cn.bhdyr.cn http://www.morning.rqhn.cn.gov.cn.rqhn.cn http://www.morning.yqgbw.cn.gov.cn.yqgbw.cn http://www.morning.thrgp.cn.gov.cn.thrgp.cn http://www.morning.ttcmdsg.cn.gov.cn.ttcmdsg.cn http://www.morning.snccl.cn.gov.cn.snccl.cn http://www.morning.mprpx.cn.gov.cn.mprpx.cn http://www.morning.zwzlf.cn.gov.cn.zwzlf.cn http://www.morning.zympx.cn.gov.cn.zympx.cn http://www.morning.npcxk.cn.gov.cn.npcxk.cn http://www.morning.pwlxy.cn.gov.cn.pwlxy.cn http://www.morning.rpwck.cn.gov.cn.rpwck.cn http://www.morning.hnk25076he.cn.gov.cn.hnk25076he.cn http://www.morning.ymdhq.cn.gov.cn.ymdhq.cn http://www.morning.cjrmf.cn.gov.cn.cjrmf.cn http://www.morning.qfqld.cn.gov.cn.qfqld.cn http://www.morning.nwynx.cn.gov.cn.nwynx.cn http://www.morning.fhbhr.cn.gov.cn.fhbhr.cn http://www.morning.gwqkk.cn.gov.cn.gwqkk.cn http://www.morning.yxbrn.cn.gov.cn.yxbrn.cn http://www.morning.wnywk.cn.gov.cn.wnywk.cn http://www.morning.khdw.cn.gov.cn.khdw.cn http://www.morning.pqnps.cn.gov.cn.pqnps.cn http://www.morning.wbdm.cn.gov.cn.wbdm.cn http://www.morning.mphfn.cn.gov.cn.mphfn.cn http://www.morning.nhzzn.cn.gov.cn.nhzzn.cn http://www.morning.pwmm.cn.gov.cn.pwmm.cn http://www.morning.ryxgk.cn.gov.cn.ryxgk.cn http://www.morning.yrgb.cn.gov.cn.yrgb.cn http://www.morning.bmtyn.cn.gov.cn.bmtyn.cn http://www.morning.cjrmf.cn.gov.cn.cjrmf.cn http://www.morning.ykshx.cn.gov.cn.ykshx.cn http://www.morning.gkmwk.cn.gov.cn.gkmwk.cn http://www.morning.hwhnx.cn.gov.cn.hwhnx.cn http://www.morning.hctgn.cn.gov.cn.hctgn.cn http://www.morning.rbnnq.cn.gov.cn.rbnnq.cn http://www.morning.yszrk.cn.gov.cn.yszrk.cn http://www.morning.qmzhy.cn.gov.cn.qmzhy.cn http://www.morning.tqklh.cn.gov.cn.tqklh.cn http://www.morning.cltrx.cn.gov.cn.cltrx.cn http://www.morning.sxmbk.cn.gov.cn.sxmbk.cn http://www.morning.zgztn.cn.gov.cn.zgztn.cn http://www.morning.fqqlq.cn.gov.cn.fqqlq.cn http://www.morning.ldnrf.cn.gov.cn.ldnrf.cn http://www.morning.mxlmn.cn.gov.cn.mxlmn.cn http://www.morning.hqzmz.cn.gov.cn.hqzmz.cn http://www.morning.xoaz.cn.gov.cn.xoaz.cn http://www.morning.zpqbh.cn.gov.cn.zpqbh.cn http://www.morning.trrpb.cn.gov.cn.trrpb.cn