1 Star 0 Fork 0

robertzhai / go_common

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
client.go 5.75 KB
一键复制 编辑 原始数据 按行查看 历史
robertzhai 提交于 2023-06-16 12:07 . update
// Package httpclient 提供简单易用的http library 包装自 github.com/go-resty/resty
package httpclient
import (
"net"
"net/http"
"runtime"
"time"
"github.com/go-resty/resty/v2"
)
var (
//header key
HdrUserAgentKey = http.CanonicalHeaderKey("User-Agent")
HdrAcceptKey = http.CanonicalHeaderKey("Accept")
HdrContentTypeKey = http.CanonicalHeaderKey("Content-Type")
HdrContentLengthKey = http.CanonicalHeaderKey("Content-Length")
HdrContentEncodingKey = http.CanonicalHeaderKey("Content-Encoding")
HdrAuthorizationKey = http.CanonicalHeaderKey("Authorization")
PlainTextType = "text/plain; charset=utf-8"
JSONContentType = "application/json"
FormContentType = "application/x-www-form-urlencoded"
hdrUserAgentValue = "Go-http-client/1.1"
)
// HTTPClient resty.Client的封装
type HTTPClient struct {
client *resty.Client
}
func NewHTTPClient(transport *http.Transport) *HTTPClient {
httpClient := New()
httpClient.SetTransport(transport)
return httpClient
}
var logTag = "net.httpclient"
// 监控记录
type RequestTimeRecord struct {
app string
cost int64
status string
domain string
uri string
}
func formatStatus(status string) string {
if status == "" {
return "nil"
}
if len(status) > 3 {
return status[0:3]
}
return status
}
// 默认响应后置钩子函数
var defaultAfterResponseHook resty.ResponseMiddleware = func(c *resty.Client, resp *resty.Response) error {
return nil
}
// New 初始化HTTPClient
func New() *HTTPClient {
hc := &HTTPClient{client: resty.New()}
hc.SetHeader(HdrUserAgentKey, hdrUserAgentValue)
hc.OnAfterResponseHook(defaultAfterResponseHook)
return hc
}
//指定监控apikey, 例如下载图片,否则每次请求启动一个monitorResponseTime, 导致内存泄露
func NewByApiKey(apiKey string) *HTTPClient {
hc := &HTTPClient{client: resty.New()}
hc.SetHeader(HdrUserAgentKey, hdrUserAgentValue)
f := func(c *resty.Client, resp *resty.Response) error {
return nil
}
hc.OnAfterResponseHook(f)
return hc
}
// Request 初始化
func (hc *HTTPClient) Request() *HTTPRequest {
return &HTTPRequest{
request: hc.client.R(),
httpclient: hc,
}
}
// OnBeforeRequestHook 装载请求前置钩子
func (hc *HTTPClient) OnBeforeRequestHook(f resty.RequestMiddleware) *HTTPClient {
hc.client = hc.client.OnBeforeRequest(f)
return hc
}
// OnAfterResponseHook 装载响应后置钩子(响应报err不会执行到此hook)
func (hc *HTTPClient) OnAfterResponseHook(f resty.ResponseMiddleware) *HTTPClient {
hc.client = hc.client.OnAfterResponse(f)
return hc
}
func (hc *HTTPClient) SetPreRequestHook(f resty.PreRequestHook) *HTTPClient {
hc.client = hc.client.SetPreRequestHook(f)
return hc
}
// SetHeader 设置Header, Request SetHeader可以覆盖此设置
func (hc *HTTPClient) SetHeader(header, value string) *HTTPClient {
hc.client.Header[header] = []string{value}
return hc
}
// SetHeaders 设置多个Header字段, Request SetHeaders可以覆盖此设置
// 一个client instance 可以发起多个Request
func (hc *HTTPClient) SetHeaders(headers map[string]string) *HTTPClient {
// 由于http.Header.Set方法对于传入的key会强制首字母大写
// 对于不规范的自定义header会存在问题,所以此处没有直接使用http.Header.Set方法
for h, v := range headers {
hc.client.Header[h] = []string{v}
}
return hc
}
// SetHostURL 设置host url
// Setting HTTP address SetHostURL("http://babytree.com")
// Setting HTTPS address SetHostURL("https://babytree.com")
func (hc *HTTPClient) SetHostURL(url string) *HTTPClient {
hc.client = hc.client.SetHostURL(url)
return hc
}
// SetQueryParam 设置query参数, Request SetQueryParam可以覆盖此设置
// 一个client instance 可以发起多个Request,一般公共参数用此方法
func (hc *HTTPClient) SetQueryParam(param, value string) *HTTPClient {
hc.client = hc.client.SetQueryParam(param, value)
return hc
}
// SetQueryParams 设置多个query参数, Request SetQueryParams可以覆盖此设置
func (hc *HTTPClient) SetQueryParams(params map[string]string) *HTTPClient {
hc.client = hc.client.SetQueryParams(params)
return hc
}
// SetPathParams 设置动态url path, Request SetPathParams可以覆盖此设置
func (hc *HTTPClient) SetPathParams(params map[string]string) *HTTPClient {
hc.client = hc.client.SetPathParams(params)
return hc
}
func (hc *HTTPClient) SetDebug(d bool) *HTTPClient {
hc.client = hc.client.SetDebug(d)
return hc
}
func (hc *HTTPClient) SetLogger(l resty.Logger) *HTTPClient {
hc.client = hc.client.SetLogger(l)
return hc
}
// SetFormData 设置Form data Request SetFormData可以覆盖此设置
func (hc *HTTPClient) SetFormData(data map[string]string) *HTTPClient {
hc.client = hc.client.SetFormData(data)
return hc
}
// SetTimeout 设置超时
func (hc *HTTPClient) SetTimeout(timeout time.Duration) *HTTPClient {
hc.client = hc.client.SetTimeout(timeout)
return hc
}
// SetTransport 设置http.Transport
func (hc *HTTPClient) SetTransport(transport *http.Transport) *HTTPClient {
if transport == nil {
return hc
}
if transport.Proxy == nil {
transport.Proxy = http.ProxyFromEnvironment
}
if transport.DialContext == nil {
dialer := &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}
transport.DialContext = dialer.DialContext
}
if transport.MaxIdleConns == 0 {
transport.MaxIdleConns = 100
}
if transport.IdleConnTimeout == 0 {
transport.IdleConnTimeout = 90 * time.Second
}
if transport.TLSHandshakeTimeout == 0 {
transport.TLSHandshakeTimeout = 10 * time.Second
}
if transport.ExpectContinueTimeout == 0 {
transport.ExpectContinueTimeout = time.Second
}
if transport.MaxIdleConnsPerHost == 0 {
transport.MaxIdleConnsPerHost = runtime.GOMAXPROCS(0) + 1
}
hc.client = hc.client.SetTransport(transport)
return hc
}
Go
1
https://gitee.com/home_robertzhai/go_common.git
git@gitee.com:home_robertzhai/go_common.git
home_robertzhai
go_common
go_common
v1.1.0

搜索帮助

53164aa7 5694891 3bd8fe86 5694891