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. 每日CSS_发光文本效果

    每日CSS_发光文本效果 2020_12_22 源码 1. 代码解析 1.1 html 代码片段 <h1> <span>今</span> <span>天 ...

  2. 豆瓣读书top250数据爬取与可视化

    爬虫–scrapy 题目:根据豆瓣读书top250,根据出版社对书籍数量分类,绘制饼图 搭建环境 import scrapy import numpy as np import pandas as p ...

  3. 解决uiautomator截取不到手机App界面信息

    今天在使用uiautomatorviewer进行安卓app控件定位的时候,出现以下异常,(用的是真机测试Android版本是10,据说是Android 8以后sdk自带的uiautomator直接打开 ...

  4. Tensorflow环境配置&安装

    Tensorflow环境配置&安装 明知故犯,是不想有遗憾. 背景:Tensorflow 环境配置和安装. 一.安装 Anaconda 二.建立.激活.安装.验证.使用 Tensorflow ...

  5. 【进程/作业管理】篇章一:Linux进程及其管理(进程管理类工具)----pstree、ps、top、htop、kill、(killall、pkill、pgrep、pidof)

    主要讲解进程管理类命令及工具的使用:pstree.ps.top.htop.kill.(killall.pkill.pgrep.pidof) pstree 以树状图的方式展现进程之间的派生关系,显示效果 ...

  6. Azure Terraform(一)入门简介

    一,引言 众所周知,当企业将项目整体架构资源迁移到云上,云基础设施架构师就要根据现有项目搭建整体项目的基础设施资源的架构,然后我们的云运维工程师就要根据设计好基础设施的架构图来创建云上资源,但是在构筑 ...

  7. 卷积网络可解释性复现 | Grad-CAM | ICCV | 2017

    觉得本文不错的可以点个赞.有问题联系作者微信cyx645016617,之后主要转战公众号,不在博客园和CSDN更新. 论文名称:"Grad-CAM: Visual Explanations ...

  8. PDO实用

    $sql="select * from test4 "; $b = $pdo->query($sql); // 返回的是个新对象 $c =$b->fetchAll(); ...

  9. SpringMVC+JPA+SpringData配置

    <properties>   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  ...

  10. Linux服务器上搭建测试环境(war包+tomcat)

    悟空CRM项目环境部署(Java war项目) 在/root目录下创建一个文件夹(名字自取). ls命令查看一下是否创建成功,看到了新建的文件夹说明创建成功. tomcat和war包的准备:可以使用X ...