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 常用操作的更多相关文章

  1. 【三】用Markdown写blog的常用操作

    本系列有五篇:分别是 [一]Ubuntu14.04+Jekyll+Github Pages搭建静态博客:主要是安装方面 [二]jekyll 的使用 :主要是jekyll的配置 [三]Markdown+ ...

  2. php模拟数据库常用操作效果

    test.php <?php header("Content-type:text/html;charset='utf8'"); error_reporting(E_ALL); ...

  3. Mac OS X常用操作入门指南

    前两天入手一个Macbook air,在装软件过程中摸索了一些基本操作,现就常用操作进行总结, 1关于触控板: 按下(不区分左右)            =鼠标左键 control+按下        ...

  4. mysql常用操作语句

    mysql常用操作语句 1.mysql -u root -p   2.mysql -h localhost -u root -p database_name 2.列出数据库: 1.show datab ...

  5. nodejs配置及cmd常用操作

    一.cmd常用操作 1.返回根目录cd\ 2.返回上层目录cd .. 3.查找当前目录下的所有文件dir 4.查找下层目录cd window 二.nodejs配置 Node.js安装包及源码下载地址为 ...

  6. Oracle常用操作——创建表空间、临时表空间、创建表分区、创建索引、锁表处理

    摘要:Oracle数据库的库表常用操作:创建与添加表空间.临时表空间.创建表分区.创建索引.锁表处理 1.表空间 ■  详细查看表空间使用状况,包括总大小,使用空间,使用率,剩余空间 --详细查看表空 ...

  7. python 异常处理、文件常用操作

    异常处理 http://www.jb51.net/article/95033.htm 文件常用操作 http://www.jb51.net/article/92946.htm

  8. byte数据的常用操作函数[转发]

    /// <summary> /// 本类提供了对byte数据的常用操作函数 /// </summary> public class ByteUtil { ','A','B',' ...

  9. Linux Shell数组常用操作详解

    Linux Shell数组常用操作详解 1数组定义: declare -a 数组名 数组名=(元素1 元素2 元素3 ) declare -a array array=( ) 数组用小括号括起,数组元 ...

随机推荐

  1. B. Navigation System【CF 1320】

    传送门 题目:简单理解就是,我们需要开车从s点到t点.车上有一个导航,如果当前点为x,则导航会自动为你提供一条从x到t的最短的路线(如果有多条,则随机选一条),每走到下一个点则会实时更新最短路线,当然 ...

  2. Unity使用小剧场—创建的按钮On Click()只有MonoScript怎么办

    前言: 在游戏开发过程中遇到了一些小问题,以后都放到小剧场里,今天介绍怎么给按钮赋予方法并解决标题所述问题. 步骤: 1. 不管怎么说,先新建一个按钮 右键场景-[UI]-[Button] 这里会自动 ...

  3. C# IAsyncEnumerable Linq使用

    NET Core 3.0和C# 8.0最激动人心的特性之一就是IAsyncEnumerable<T>(也就是async流).但它有什么特别之处呢?我们现在可以用它做哪些以前不可能做到的事? ...

  4. sqlserver 汉字转全拼函数

    create function fn_Getquanpin (@str varchar(100)) returns varchar(8000) as begin declare @re varchar ...

  5. 查看权限详情 将部门大类单据整合,将子类单据id去重合并

    /** * 查看权限详情 * @param id 部门id * @return */ @GetMapping("getListInfo") public R getDetail(S ...

  6. Tomcat服务器的下载以及配置

    1,Tomcat的下载与安装 本人采用的是解压版安装,只需要在官网(https://tomcat.apache.org/)下载好压缩版的Tomcat,再解压在你想安装的目录下即可.我的安装目录是D:\ ...

  7. [leetcode]120.Triangle三角矩阵从顶到底的最小路径和

    Given a triangle, find the minimum path sum from top to bottom.Each step you may move to adjacent nu ...

  8. 大话MySQL锁

    一.锁介绍 不同存储引擎支持的锁是不同的,比如MyISAM只有表锁,而InnoDB既支持表锁又支持行锁. 下图展示了InnoDB不同锁类型之间的关系: 图中的概念比较多不好理解,下面依次进行说明. 1 ...

  9. eclipse 4.4安装aptana插件

    eclipse 4.4安装aptana插件: 1.地址: http://download.aptana.com/studio3/plugin/update/index.html.在线安装即可成功! 2 ...

  10. 2020DevOps状态报告——平台模型:扩展DevOps的新方法

    平台模型是我们在这个领域看到越来越多的方法,它源于负责产品或服务的端到端交付的产品团队的理念.如果只应用于单一的产品,或者几个产品,它的效果很好. 但如果有数百种产品或服务,把一个产品团队用于这些产品 ...