Golang能失败重试的HTTP Client封装库

2,914 阅读1分钟

Goreq

易用于网页、API 环境下的 Golang HTTP Client 封装库。

net/http为人类服务。

go get -u github.com/zhshch2002/goreq

Feature

  • Thread-safe | 线程安全
  • Auto Charset Decode | 自动解码
  • Easy to set proxy for each req | 便捷代理设置
  • Chain config request | 链式配置请求
  • Multipart post support
  • Parse HTML,JSON,XML | HTML、JSON、XML 解析
  • Middleware | 中间件
    • Cache | 缓存
    • Retry | 失败重试
    • Log | 日志
    • Random UserAgent | 随机 UA
    • Referer | 填充 Referer
    • Rate Delay and Parallelism limiter | 设置速率、延时、并发限制

失败重试 | WithRetry

package main

import (
	"fmt"
	"github.com/zhshch2002/goreq"
)

func main() {
	i := 0
	// 配置失败重试中间件,第二个参数函数用来检查是否为可接受的响应,传入 nil 使用默认函数。
	c := goreq.NewClient(goreq.WithRetry(10, func(resp *goreq.Response) bool {
		if i < 3 { // 为了演示模拟几次失败
			i += 1
			return false
		}
		return true
	}))
	fmt.Println(goreq.Get("https://httpbin.org/get").SetDebug(true).SetClient(c).Do().Text)
}

Output:

[Retry 1 times] got error on request https://httpbin.org/get <nil>
[Retry 2 times] got error on request https://httpbin.org/get <nil>
[Retry 3 times] got error on request https://httpbin.org/get <nil>
{
  "args": {},
  "headers": {
    "Accept-Encoding": "gzip",
    "Host": "httpbin.org",
    "User-Agent": "Go-http-client/2.0",
    "X-Amzn-Trace-Id": "Root=1-5efe9c40-bbf2d5a095e0f6d0c3aaf4c0"
  },
  "url": "https://httpbin.org/get"
}