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. vulstudy靶机搭建(kali)

    安装 安装docker apt-get install docker.io //# 安装docker pip install docker-compose //# 安装docker-compose g ...

  2. 从零到一快速搭建个人博客网站(域名自动跳转www,二级域名使用)(二)

    前言 本篇文章是对上篇文章从零到一快速搭建个人博客网站(域名备案 + https免费证书)(一)的完善,比如域名自动跳转www.二级域名使用等. 域名自动跳转www 这里对上篇域名访问进行优化,首先支 ...

  3. 第九章 Nacos Config--服务配置

    今天咱们接着 上一篇 第八章 SMS–短信服务 继续写 SpringCloud Alibaba全家桶 -> 第九章 Nacos Config–服务配置,废话不多说,开干 9.1 服务配置中心介绍 ...

  4. 一个小技巧助您减少if语句的状态判断

    作者:依乐祝 首发地址:https://www.cnblogs.com/yilezhu/p/14174990.html 在进行项目的开发的过程中, if 语句是少不了的,但我们始终要有一颗消灭 if  ...

  5. python 实现数值积分与画图

    import numpy as np from scipy import integrate def half_circle(x): return (1 - x ** 2) ** 0.5 N = 10 ...

  6. Python之matplotlib画图

    折线图: Matplotlib处理csv文件 这里写两个其他的. 柱状图,柱状图个人喜欢用pygal来画,有两篇文章 - Pygal之掷骰子 和 pygal之掷骰子 - 2颗面数为6的骰子.下面用ma ...

  7. APP端有原生态的控件,但嵌入了H5页面,怎么定位到H5页面的元素

    appium 通常有很多种定位元素方法,例如xpath,driver.find_element_by_accessibility_id等,安卓sdk自带的uiautomatorviewer但是对于H5 ...

  8. Tomcat启动web项目静态页面中文乱码问题解决

    1 首先查看静态页面在编辑器中是否正常,  如果是eclipse ,需要设置一下项目编码格式为utf-8, 如果是idea , 一般会自动识别, 也可以自己手动检查一下, 检查html上面是否有    ...

  9. Springboot 添加druid监控

    pom <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifa ...

  10. .net通过iTextSharp.pdf操作pdf文件实现查找关键字签字盖章

    之前这个事情都CA公司去做的,现在给客户做demo,要模拟一下签字盖章了,我们的业务PDF文件是动态生成的所以没法通过坐标定位,只能通过关键字查找定位了. 之前在网上看了许多通多通过查询关键字,然后图 ...