Go - httpclient 常用操作
httpclient
模块介绍
httpclient 是基于 net/http 封装的 Go HTTP 客户端请求包,支持常用的请求方式、常用设置,比如:
- 支持设置 Mock 信息
- 支持设置失败时告警
- 支持设置失败时重试
- 支持设置项目内部的 Trace
- 支持设置超时时间、Header 等
请求说明
| 方法名 | 描述 |
|---|---|
| httpclient.Get() | GET 请求 |
| httpclient.Post() | POST 请求 |
| httpclient.PostForm() | POST 请求,form 形式 |
| httpclient.PostJSON() | POST 请求,json 形式 |
| httpclient.PutForm() | PUT 请求,form 形式 |
| httpclient.PutJSON() | PUT 请求,json 形式 |
| httpclient.PatchForm() | PATCH 请求,form 形式 |
| httpclient.PatchJSON() | PATCH 请求,json 形式 |
| httpclient.Delete() | DELETE 请求 |
配置说明
| 配置项 | 配置方法 |
|---|---|
| 设置 TTL 本次请求最大超时时间 | httpclient.WithTTL(ttl time.Duration) |
| 设置 Header 信息 | httpclient.WithHeader(key, value string) |
| 设置 Logger 信息 | httpclient.WithLogger(logger *zap.Logger) |
| 设置 Trace 信息 | httpclient.WithTrace(t trace.T) |
| 设置 Mock 信息 | httpclient.WithMock(m Mock) |
| 设置失败时告警 | httpclient.WithOnFailedAlarm(alarmTitle string, alarmObject AlarmObject, alarmVerify AlarmVerify) |
| 设置失败时重试 | httpclient.WithOnFailedRetry(retryTimes int, retryDelay time.Duration, retryVerify RetryVerify) |
设置 TTL
// 设置本次请求最大超时时间为 5s
httpclient.WithTTL(time.Second*5),
设置 Header 信息
可以调用多次进行设置多对 key-value 信息。
// 设置多对 key-value 信息,比如这样:
httpclient.WithHeader("Authorization", "xxxx"),
httpclient.WithHeader("Date", "xxxx"),
设置 Logger 信息
传递的 logger 便于 httpclient 打印日志。
// 使用上下文中的 logger,比如这样:
httpclient.WithLogger(ctx.Logger()),
设置 Trace 信息
传递的 trace 便于记录使用 httpclient 调用第三方接口的链路日志。
// 使用上下文中的 trace,比如这样:
httpclient.WithTrace(ctx.Trace()),
设置 Mock 信息
// Mock 类型
type Mock func() (body []byte)
// 需实现 Mock 方法,比如这样:
func MockDemoPost() (body []byte) {
res := new(demoPostResponse)
res.Code = 1
res.Msg = "ok"
res.Data.Name = "mock_Name"
res.Data.Job = "mock_Job"
body, _ = json.Marshal(res)
return body
}
// 使用时:
httpclient.WithMock(MockDemoPost),
传递的 Mock 方式便于设置调用第三方接口的 Mock 数据。只要约定了接口文档,即使对方接口未开发时,也不影响数据联调。
设置失败时告警
// alarmTitle 设置失败告警标题 String
// AlarmObject 告警通知对象,可以是邮件、短信或微信
type AlarmObject interface {
Send(subject, body string) error
}
// 需要去实现 AlarmObject 接口,比如这样:
var _ httpclient.AlarmObject = (*AlarmEmail)(nil)
type AlarmEmail struct{}
func (a *AlarmEmail) Send(subject, body string) error {
options := &mail.Options{
MailHost: "smtp.163.com",
MailPort: 465,
MailUser: "xx@163.com",
MailPass: "",
MailTo: "",
Subject: subject,
Body: body,
}
return mail.Send(options)
}
// AlarmVerify 定义符合告警的验证规则
type AlarmVerify func(body []byte) (shouldAlarm bool)
// 需要去实现 AlarmVerify 方法,比如这样:
func alarmVerify(body []byte) (shouldalarm bool) {
if len(body) == 0 {
return true
}
type Response struct {
Code int `json:"code"`
}
resp := new(Response)
if err := json.Unmarshal(body, resp); err != nil {
return true
}
// 当第三方接口返回的 code 不等于约定的成功值(1)时,就要进行告警
return resp.Code != 1
}
// 使用时:
httpclient.WithOnFailedAlarm("接口告警", new(third_party_request.AlarmEmail), alarmVerify),
设置失败时重试
// retryTimes 设置重试次数 Int,默认:3
// retryDelay 设置重试前延迟等待时间 time.Duration,默认:time.Millisecond * 100
// RetryVerify 定义符合重试的验证规则
type RetryVerify func(body []byte) (shouldRetry bool)
// 需要去实现 RetryVerify 方法,比如这样:
func retryVerify(body []byte) (shouldRetry bool) {
if len(body) == 0 {
return true
}
type Response struct {
Code int `json:"code"`
}
resp := new(Response)
if err := json.Unmarshal(body, resp); err != nil {
return true
}
// 当第三方接口返回的 code 等于约定值(10010)时,就要进行重试
return resp.Code = 10010
}
// RetryVerify 也可以为 nil , 当为 nil 时,默认重试规则为 http_code 为如下情况:
// http.StatusRequestTimeout, 408
// http.StatusLocked, 423
// http.StatusTooEarly, 425
// http.StatusTooManyRequests, 429
// http.StatusServiceUnavailable, 503
// http.StatusGatewayTimeout, 504
// 使用时:
httpclient.WithOnFailedRetry(3, time.Second*1, retryVerify),
示例代码
// 以 httpclient.PostForm 为例
api := "http://127.0.0.1:9999/demo/post"
params := url.Values{}
params.Set("name", name)
body, err := httpclient.PostForm(api, params,
httpclient.WithTTL(time.Second*5),
httpclient.WithTrace(ctx.Trace()),
httpclient.WithLogger(ctx.Logger()),
httpclient.WithHeader("Authorization", "xxxx"),
httpclient.WithMock(MockDemoPost),
httpclient.WithOnFailedRetry(3, time.Second*1, retryVerify),
httpclient.WithOnFailedAlarm("接口告警", new(third_party_request.AlarmEmail), alarmVerify),
)
if err != nil {
return nil, err
}
res = new(demoPostResponse)
err = json.Unmarshal(body, res)
if err != nil {
return nil, errors.Wrap(err, "DemoPost json unmarshal error")
}
if res.Code != 1 {
return nil, errors.New(fmt.Sprintf("code err: %d-%s", res.Code, res.Msg))
}
return res, nil
以上代码在 go-gin-api 项目中,地址:https://github.com/xinliangnote/go-gin-api
Go - httpclient 常用操作的更多相关文章
- 【三】用Markdown写blog的常用操作
本系列有五篇:分别是 [一]Ubuntu14.04+Jekyll+Github Pages搭建静态博客:主要是安装方面 [二]jekyll 的使用 :主要是jekyll的配置 [三]Markdown+ ...
- php模拟数据库常用操作效果
test.php <?php header("Content-type:text/html;charset='utf8'"); error_reporting(E_ALL); ...
- Mac OS X常用操作入门指南
前两天入手一个Macbook air,在装软件过程中摸索了一些基本操作,现就常用操作进行总结, 1关于触控板: 按下(不区分左右) =鼠标左键 control+按下 ...
- mysql常用操作语句
mysql常用操作语句 1.mysql -u root -p 2.mysql -h localhost -u root -p database_name 2.列出数据库: 1.show datab ...
- nodejs配置及cmd常用操作
一.cmd常用操作 1.返回根目录cd\ 2.返回上层目录cd .. 3.查找当前目录下的所有文件dir 4.查找下层目录cd window 二.nodejs配置 Node.js安装包及源码下载地址为 ...
- Oracle常用操作——创建表空间、临时表空间、创建表分区、创建索引、锁表处理
摘要:Oracle数据库的库表常用操作:创建与添加表空间.临时表空间.创建表分区.创建索引.锁表处理 1.表空间 ■ 详细查看表空间使用状况,包括总大小,使用空间,使用率,剩余空间 --详细查看表空 ...
- python 异常处理、文件常用操作
异常处理 http://www.jb51.net/article/95033.htm 文件常用操作 http://www.jb51.net/article/92946.htm
- byte数据的常用操作函数[转发]
/// <summary> /// 本类提供了对byte数据的常用操作函数 /// </summary> public class ByteUtil { ','A','B',' ...
- Linux Shell数组常用操作详解
Linux Shell数组常用操作详解 1数组定义: declare -a 数组名 数组名=(元素1 元素2 元素3 ) declare -a array array=( ) 数组用小括号括起,数组元 ...
随机推荐
- SpringBoot执行原理
目录 [Toc] 一.执行原理: 每个Spring Boot项目都有一个主程序启动类,在主程序启动类中有一个启动项目的main()方法, 在该方法中通过执行SpringApplication.run( ...
- 爬取并分析一下B站的最热视频排行榜,看看大家都喜欢看什么视频
前言 现在大家的生活中,已经越来越离不开B站了,2020年的第一季度,B站月活跃用户达到了1.72亿,日活跃用户也已经突破了5000万个用户.源源不断的流量让B站的up主们也是粉丝数目不断暴涨,百万粉 ...
- linux操作系统及常用命令
GUN:GUN is Not UnixGPL:General Public License.通用公共许可证,版权 Copyright,Copyleft 开源协议LGPL:lesserGPLv2GPLv ...
- MVC中使用T4模板
参考博文 http://www.cnblogs.com/heyuquan/archive/2012/07/26/2610959.html 图片释义 1.简单示例,对基本的模块标记 2.根据上图生成的类 ...
- Jenkins自动化部署服务器及git 提交及git tag标签版本更新流程,超详细!
工作中部署的项目和服务器较多时就用上了Jenkins进行自动部署 优点 不用在连接单独的服务器进行更新项目,再启动项目服务的操作了 更新部署都是自动的,比较方便.适合大批量的部署 一.git流程部分 ...
- 160个Crackerme破解
001: 第一个破解: 有两种登陆方式:序列号/名字和序列号,观察报错信息 两个报错信息,直接中文搜索字符: 第一种登陆方式报错为:sorry,xx 右键中文字符搜索,ctrl+f输入要搜索的字符,这 ...
- Java学习_面向对象编程
抽象类 一个class定义了方法,但没有具体执行代码,这个方法就是抽象方法,抽象方法用abstract修饰.因为抽象类本身被设计成只能用于被继承,因此,抽象类可以强迫子类实现其定义的抽象方法,否则编译 ...
- [leetcode]720. Longest Word in Dictionary字典中最长的单词
b.compareTo(a) 这个函数是比较两个值得大小,如果b比a大,那么返回1 如果小,那么返回-1,相等返回0 如果比较的是字符串,那么比较字典编纂顺序,b靠前返回-1,靠后返回1 这个题的核心 ...
- 网页短信平台源码和开发功能介绍 思路和功能 G客短信平台
G客短信源码介绍 (只介绍现有功能模块文字介绍配系统截图) 一:后台首页 QQ:290615413 VX:290615413
- Linux下Oracle 11G XE 安装笔记
操作系统 [oracle@RAC02 ~]$ lsb_release -aLSB Version: :base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:cor ...