Documentation
¶
Overview ¶
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-28 18:55:55 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-08-20 16:33:01 * @FilePath: \go-toolbox\pkg\httpx\client.go * @Description: HTTP 客户端实现 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-28 18:55:55 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-30 15:26:55 * @FilePath: \go-toolbox\pkg\httpx\error.go * @Description: HTTP 相关错误定义 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-01-05 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-01-05 11:32:06 * @FilePath: \go-toolbox\pkg\httpx\helpers.go * @Description: HTTP 辅助方法 * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-01-16 13:30:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-01-16 21:11:58 * @FilePath: \go-toolbox\pkg\httpx\params.go * @Description: 参数构建器 * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-28 18:55:55 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-30 20:17:08 * @FilePath: \go-toolbox\pkg\httpx\request.go * @Description: HTTP 请求封装 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-28 18:55:55 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-05-27 15:05:08 * @FilePath: \go-toolbox\pkg\httpx\response.go * @Description: HTTP 响应封装 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-28 18:55:55 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-28 18:55:55 * @FilePath: \go-toolbox\pkg\httpx\types.go * @Description: HTTP 相关常量和类型定义 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2026-01-16 21:50:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-01-16 21:50:00 * @FilePath: \go-toolbox\pkg\httpx\url.go * @Description: URL 处理工具函数 * * Copyright (c) 2026 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-28 18:55:55 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-30 20:17:08 * @FilePath: \go-toolbox\pkg\httpx\validator.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
Index ¶
- Constants
- func BuildParams(base map[string]string, opts ...func(map[string]string)) map[string]string
- func DecodeRespBody(resp *Response, dst any) error
- func GetCookies(url string) ([]*http.Cookie, error)
- func GetRequestValue(r *http.Request, contextKey interface{}, headerName, queryName string) string
- func GetValueFromHeaderOrQuery(r *http.Request, headerName, queryName string) string
- func IsValidMethod(method string) bool
- func NormalizeBaseURL(baseURL string) string
- func ReadAndCacheResponseBody(resp *http.Response) (string, error)
- func ReadRequestBody(r *http.Request) ([]byte, error)
- func WithParam(condition bool, key, value string) func(map[string]string)
- func WithParamNotEmpty(key, value string) func(map[string]string)
- type BodyEncodeFunc
- type Client
- func NewClient(opts ...ClientOption) *Client
- func NewClientWithContext(client *http.Client, ctx context.Context) *Client
- func NewCustomDefaultClient() *Client
- func NewCustomDefaultClientWithContext(ctx context.Context) *Client
- func NewDefaultHttpClient() *Client
- func NewDefaultHttpClientWithContext(ctx context.Context) *Client
- func NewHttpClient(client *http.Client) *Client
- func (c *Client) Connect(endpoint string) *Request
- func (c *Client) Delete(endpoint string) *Request
- func (c *Client) Get(endpoint string) *Request
- func (c *Client) Head(endpoint string) *Request
- func (c *Client) NewRequest(method, endpoint string) *Request
- func (c *Client) Options(endpoint string) *Request
- func (c *Client) Patch(endpoint string) *Request
- func (c *Client) Post(endpoint string) *Request
- func (c *Client) Put(endpoint string) *Request
- func (c *Client) Trace(endpoint string) *Request
- type ClientOption
- func WithContext(ctx context.Context) ClientOption
- func WithIdleConnTimeout(timeout time.Duration) ClientOption
- func WithInsecureSkipVerify(skip bool) ClientOption
- func WithMaxConnsPerHost(n int) ClientOption
- func WithMaxIdleConns(n int) ClientOption
- func WithMaxIdleConnsPerHost(n int) ClientOption
- func WithTLSHandshakeTimeout(timeout time.Duration) ClientOption
- func WithTimeout(timeout time.Duration) ClientOption
- type FileField
- type ParamsBuilder
- func (b *ParamsBuilder) Add(key, value string) *ParamsBuilder
- func (b *ParamsBuilder) Build() map[string]string
- func (b *ParamsBuilder) Clear() *ParamsBuilder
- func (b *ParamsBuilder) Clone() *ParamsBuilder
- func (b *ParamsBuilder) Delete(key string) *ParamsBuilder
- func (b *ParamsBuilder) Get(key string) (string, bool)
- func (b *ParamsBuilder) Has(key string) bool
- func (b *ParamsBuilder) Keys() []string
- func (b *ParamsBuilder) Len() int
- func (b *ParamsBuilder) Merge(other *ParamsBuilder) *ParamsBuilder
- func (b *ParamsBuilder) Set(key, value string) *ParamsBuilder
- func (b *ParamsBuilder) SetAny(key string, value interface{}) *ParamsBuilder
- func (b *ParamsBuilder) SetAnyIf(condition bool, key string, value interface{}) *ParamsBuilder
- func (b *ParamsBuilder) SetIf(condition bool, key, value string) *ParamsBuilder
- func (b *ParamsBuilder) SetMultiple(params map[string]string) *ParamsBuilder
- func (b *ParamsBuilder) SetNotEmpty(key, value string) *ParamsBuilder
- func (b *ParamsBuilder) ToSlice() []interface{}
- func (b *ParamsBuilder) Values() []string
- type Request
- func (r *Request) AddCookie(cookie *http.Cookie) *Request
- func (r *Request) AddHeader(key, value string) *Request
- func (r *Request) AddHeaders(headers map[string]string) *Request
- func (r *Request) AddQueries(queries map[string]string) *Request
- func (r *Request) AddQuery(key, value string) *Request
- func (r *Request) Client() *http.Client
- func (r *Request) Clone() *Request
- func (r *Request) Context() context.Context
- func (r *Request) Cookie(name string) (*http.Cookie, error)
- func (r *Request) Do(ctx context.Context) ([]byte, error)
- func (r *Request) FullURL() string
- func (r *Request) GetBody() any
- func (r *Request) GetBodyBytes() io.Reader
- func (r *Request) GetBodyEncodeFunc() BodyEncodeFunc
- func (r *Request) GetClient() *http.Client
- func (r *Request) GetCtx() context.Context
- func (r *Request) GetError() error
- func (r *Request) GetFullURL() string
- func (r *Request) GetHeaders() http.Header
- func (r *Request) GetMethod() string
- func (r *Request) GetQueryValues() url.Values
- func (r *Request) GetURL() string
- func (r *Request) Header() http.Header
- func (r *Request) Method() string
- func (r *Request) MustSend() Response
- func (r *Request) Send() (Response, error)
- func (r *Request) SetAccept(accept string) *Request
- func (r *Request) SetAuthorization(token string) *Request
- func (r *Request) SetBearerToken(token string) *Request
- func (r *Request) SetBody(body any) *Request
- func (r *Request) SetBodyEncodeFunc(fn BodyEncodeFunc) *Request
- func (r *Request) SetBodyForm(data url.Values) *Request
- func (r *Request) SetBodyJSON(body any) *Request
- func (r *Request) SetBodyMultipart(fieldName, fileName string, fileContent []byte) *Request
- func (r *Request) SetBodyMultipartWithFields(fields map[string]string, files map[string]FileField) *Request
- func (r *Request) SetBodyRaw(body []byte) *Request
- func (r *Request) SetBodyString(body string) *Request
- func (r *Request) SetContentType(contentType string) *Request
- func (r *Request) SetEndpoint(endpoint string) *Request
- func (r *Request) SetHeader(key, value string) *Request
- func (r *Request) SetHeaders(headers map[string]string) *Request
- func (r *Request) SetQueries(queries map[string]string) *Request
- func (r *Request) SetQuery(key, value string) *Request
- func (r *Request) SetQueryValues(values url.Values) *Request
- func (r *Request) SetUserAgent(userAgent string) *Request
- func (r *Request) URL() string
- func (r *Request) WithContext(ctx context.Context) *Request
- type Response
- func (r *Response) Body() ([]byte, error)
- func (r *Response) Bytes() ([]byte, error)
- func (r *Response) CheckStatus() error
- func (r *Response) Close() error
- func (r *Response) Decode(dst any) error
- func (r *Response) DecodeRespBody(dst any) error
- func (r *Response) Error() error
- func (r *Response) GetBody() ([]byte, error)
- func (r *Response) GetCookies() ([]*http.Cookie, error)
- func (r *Response) GetError() error
- func (r *Response) IsError() bool
- func (r *Response) JSON(dst any) error
- func (r *Response) LogResponse()
- func (r *Response) OK() bool
- func (r *Response) String() (string, error)
- func (r *Response) XML(dst any) error
Constants ¶
const ( ErrUnsupportedContentType errorx.ErrorType = 30000 + iota // 不支持的内容类型 ErrInvalidMethod // 无效的请求方法 ErrBodyEncodeFuncNotSet // 请求体编码函数未设置 ErrExpectedDestinationType // 期望的目标类型不匹配 ErrRequestStatusCode // 请求状态码错误 )
const ( // HTTP Headers HeaderContentType = "Content-Type" // HTTP 请求和响应头中的 Content-Type HeaderAccept = "Accept" // HTTP 请求头中的 Accept HeaderAuthorization = "Authorization" // HTTP 请求头中的 Authorization HeaderUserAgent = "User-Agent" // HTTP 请求头中的 User-Agent HeaderCookie = "Cookie" // HTTP 请求头中的 Cookie // 常见的 Content-Type ContentTypeTextPlain = "text/plain" // 纯文本格式 ContentTypeTextPlainCharacterUTF8 = "text/plain; charset=utf-8" // UTF-8 编码的纯文本 ContentTypeApplicationJSON = "application/json" // JSON 格式 ContentTypeApplicationXNDJSON = "application/x-ndjson" // NDJSON 格式 ContentTypeApplicationXSnappyFramed = "application/x-snappy-framed" // Snappy 压缩格式的 JSON ContentTypeApplicationJSONCharacterUTF8 = "application/json; charset=utf-8" // UTF-8 编码的 JSON ContentTypeApplicationXML = "application/xml" // XML 格式 ContentTypeApplicationXMLCharacterUTF8 = "application/xml; charset=utf-8" // UTF-8 编码的 XML ContentTypeTextHTML = "text/html" // HTML 文本格式 ContentTypeTextHTMLCharacterUTF8 = "text/html; charset=utf-8" // UTF-8 编码的 HTML 文本 ContentTypeTextXML = "text/xml" // XML 文本格式 ContentTypeTextXMLCharacterUTF8 = "text/xml; charset=utf-8" // UTF-8 编码的 XML 文本 ContentTypeTextCSV = "text/csv" // CSV 文本格式 ContentTypeTextCSVCharacterUTF8 = "text/csv; charset=utf-8" // UTF-8 编码的 CSV 文本 ContentTypeImageJPEG = "image/jpeg" // JPEG 图片格式 ContentTypeImagePNG = "image/png" // PNG 图片格式 ContentTypeImageGIF = "image/gif" // GIF 图片格式 ContentTypeImageWebP = "image/webp" // WebP 图片格式 ContentTypeApplicationOctetStream = "application/octet-stream" // 二进制流格式 ContentTypeMultipartFormData = "multipart/form-data" // 表单数据格式 ContentTypeWWWFormURLEncoded = "application/x-www-form-urlencoded" // URL 编码的表单数据 )
HTTP 请求和响应相关的常量定义
Variables ¶
This section is empty.
Functions ¶
func BuildParams ¶
BuildParams 构建请求参数的辅助方法 基础参数通过 base 传入,可选参数通过 opts 传入
func DecodeRespBody ¶
DecodeRespBody 根据响应的 Content-Type 解码响应体
func GetRequestValue ¶
GetRequestValue 从 HTTP 请求中获取指定值
查找顺序: 1. 优先从上下文(Context)获取 2. 然后从请求头(Header)获取 3. 最后从查询参数(Query)获取
参数:
- r: HTTP 请求对象
- contextKey: 上下文中存储的键(可为 nil)
- headerName: 请求头中的字段名
- queryName: 查询参数中的字段名
返回:找到的值,未找到则返回空字符串
func GetValueFromHeaderOrQuery ¶
GetValueFromHeaderOrQuery 从请求头或查询参数中获取值
查找顺序: 1. 优先从请求头(Header)获取 2. 然后从查询参数(Query)获取
常用于获取签名、时间戳、Nonce 等可能在 Header 或 Query 中的参数
参数:
- r: HTTP 请求对象
- headerName: 请求头中的字段名
- queryName: 查询参数中的字段名
返回:找到的值,未找到则返回空字符串
func NormalizeBaseURL ¶
NormalizeBaseURL 规范化基础 URL,确保包含协议前缀 如果 URL 不包含 http:// 或 https:// 协议,则自动添加 https:// 参数:
- baseURL: 待规范化的基础 URL
返回:
- 规范化后的 URL,确保包含协议前缀
示例:
NormalizeBaseURL("www.example.com") // 返回 "https://www.example.com"
NormalizeBaseURL("example.com/api") // 返回 "https://example.com/api"
NormalizeBaseURL("http://example.com") // 返回 "http://example.com"
NormalizeBaseURL("https://example.com") // 返回 "https://example.com"
NormalizeBaseURL("") // 返回 ""
func ReadAndCacheResponseBody ¶
ReadAndCacheResponseBody 读取并缓存响应体
func ReadRequestBody ¶
ReadRequestBody 读取 HTTP 请求体(支持重复读取)
读取后会重新设置请求体,使其可以被后续处理器再次读取 这对于需要多次访问请求体的中间件(如签名验证、日志记录)非常有用
参数:
- r: HTTP 请求对象
返回:
- 请求体内容(字节数组)
- 读取错误(如果有)
注意:如果请求体为 nil,返回 (nil, nil)
func WithParamNotEmpty ¶
WithParamNotEmpty 非空时添加参数
Types ¶
type BodyEncodeFunc ¶
BodyEncodeFunc 定义请求体编码函数类型 该函数接收任意类型的请求体并返回 io.Reader 和可能的错误
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client 是一个封装 http.Client 的结构体
func NewClientWithContext ¶
NewClientWithContext 创建一个使用自定义 http.Client 和自定义上下文的 Client 实例
func NewCustomDefaultClient ¶
func NewCustomDefaultClient() *Client
NewCustomDefaultClient 创建一个使用自定义配置的 http.Client 的 Client 实例,默认上下文为 context.Background()
func NewCustomDefaultClientWithContext ¶
NewCustomDefaultClientWithContext 创建一个使用自定义配置的 http.Client 和自定义上下文的 Client 实例
func NewDefaultHttpClient ¶
func NewDefaultHttpClient() *Client
NewDefaultHttpClient 创建一个使用默认 http.Client 的 Client 实例,默认上下文为 context.Background()
func NewDefaultHttpClientWithContext ¶
NewDefaultHttpClientWithContext 创建一个使用默认 http.Client 和自定义上下文的 Client 实例
func NewHttpClient ¶
NewHttpClient 创建一个使用自定义 http.Client 的 Client 实例,默认上下文为 context.Background()
func (*Client) NewRequest ¶
NewRequest 创建一个新的 HTTP 请求封装 Request 实例
type ClientOption ¶
type ClientOption func(*clientConfig)
ClientOption 客户端选项函数
func WithIdleConnTimeout ¶
func WithIdleConnTimeout(timeout time.Duration) ClientOption
WithIdleConnTimeout 设置空闲连接超时时间
func WithInsecureSkipVerify ¶
func WithInsecureSkipVerify(skip bool) ClientOption
WithInsecureSkipVerify 设置是否跳过 TLS 证书验证(生产环境慎用)
func WithMaxConnsPerHost ¶
func WithMaxConnsPerHost(n int) ClientOption
WithMaxConnsPerHost 设置每个主机最大连接数
func WithMaxIdleConnsPerHost ¶
func WithMaxIdleConnsPerHost(n int) ClientOption
WithMaxIdleConnsPerHost 设置每个主机最大空闲连接数
func WithTLSHandshakeTimeout ¶
func WithTLSHandshakeTimeout(timeout time.Duration) ClientOption
WithTLSHandshakeTimeout 设置 TLS 握手超时时间
type ParamsBuilder ¶
type ParamsBuilder struct {
// contains filtered or unexported fields
}
ParamsBuilder 参数构建器,支持链式调用
func NewParamsWithBase ¶
func NewParamsWithBase(base map[string]string) *ParamsBuilder
NewParamsWithBase 创建带基础参数的构建器
func (*ParamsBuilder) Add ¶
func (b *ParamsBuilder) Add(key, value string) *ParamsBuilder
Add 设置参数(无条件,别名)
func (*ParamsBuilder) Delete ¶
func (b *ParamsBuilder) Delete(key string) *ParamsBuilder
Delete 删除参数
func (*ParamsBuilder) Merge ¶
func (b *ParamsBuilder) Merge(other *ParamsBuilder) *ParamsBuilder
Merge 合并另一个参数构建器的参数
func (*ParamsBuilder) Set ¶
func (b *ParamsBuilder) Set(key, value string) *ParamsBuilder
Set 设置参数(无条件)
func (*ParamsBuilder) SetAny ¶
func (b *ParamsBuilder) SetAny(key string, value interface{}) *ParamsBuilder
SetAny 设置任意类型的参数值(会转换为字符串)
func (*ParamsBuilder) SetAnyIf ¶
func (b *ParamsBuilder) SetAnyIf(condition bool, key string, value interface{}) *ParamsBuilder
SetAnyIf 条件设置任意类型的参数
func (*ParamsBuilder) SetIf ¶
func (b *ParamsBuilder) SetIf(condition bool, key, value string) *ParamsBuilder
SetIf 条件设置参数
func (*ParamsBuilder) SetMultiple ¶
func (b *ParamsBuilder) SetMultiple(params map[string]string) *ParamsBuilder
SetMultiple 批量设置参数
func (*ParamsBuilder) SetNotEmpty ¶
func (b *ParamsBuilder) SetNotEmpty(key, value string) *ParamsBuilder
SetNotEmpty 非空时设置参数(使用 validator.IsEmptyValue 判断)
func (*ParamsBuilder) ToSlice ¶
func (b *ParamsBuilder) ToSlice() []interface{}
ToSlice 将参数转换为 []interface{} 格式,用于日志记录 返回格式: []interface{}{"key1", "value1", "key2", "value2", ...}
type Request ¶
type Request struct {
// contains filtered or unexported fields
}
Request 结构体用于封装 HTTP 请求的相关信息
func NewRequest ¶
NewRequest 创建一个新的 HTTP 请求
func (*Request) AddHeaders ¶
AddHeaders 批量添加请求头
func (*Request) AddQueries ¶
AddQueries 批量添加查询参数
func (*Request) GetBodyEncodeFunc ¶
func (r *Request) GetBodyEncodeFunc() BodyEncodeFunc
GetBodyEncodeFunc 返回自定义的请求体编码函数
func (*Request) GetFullURL ¶
GetFullURL 返回包含查询参数的完整 URL Deprecated: 使用 FullURL() 代替
func (*Request) GetQueryValues ¶
GetQueryValues 返回查询参数
func (*Request) SetAuthorization ¶
SetAuthorization 设置 Authorization
func (*Request) SetBearerToken ¶
SetBearerToken 设置 Bearer Token
func (*Request) SetBodyEncodeFunc ¶
func (r *Request) SetBodyEncodeFunc(fn BodyEncodeFunc) *Request
SetBodyEncodeFunc 设置请求体编码函数
func (*Request) SetBodyForm ¶
SetBodyForm 设置请求体为表单数据
func (*Request) SetBodyJSON ¶
SetBodyJSON 设置 JSON 请求体(自动设置 Content-Type)
func (*Request) SetBodyMultipart ¶
SetBodyMultipart 设置请求体为 multipart/form-data
func (*Request) SetBodyMultipartWithFields ¶
func (r *Request) SetBodyMultipartWithFields(fields map[string]string, files map[string]FileField) *Request
SetBodyMultipartWithFields 设置请求体为 multipart/form-data(支持多个字段)
func (*Request) SetBodyRaw ¶
SetBodyRaw 设置原始请求体,不进行任何编码
func (*Request) SetBodyString ¶
SetBodyString 设置字符串请求体
func (*Request) SetContentType ¶
SetContentType 设置 Content-Type
func (*Request) SetEndpoint ¶
SetEndpoint 设置Endpoint
func (*Request) SetHeaders ¶
SetHeaders 批量设置请求头
func (*Request) SetQueries ¶
SetQueries 批量设置查询参数
func (*Request) SetQueryValues ¶
SetBodyyValues 直接设置 url.Values
func (*Request) SetUserAgent ¶
SetUserAgent 设置 User-Agent
type Response ¶
Response 结构体用于封装 HTTP 响应
func (*Response) DecodeRespBody ¶
DecodeRespBody 解码响应体到目标结构体 Deprecated: 使用 JSON()、XML() 或 Decode() 代替
func (*Response) GetCookies ¶
GetCookies 获取响应中的 Cookie(保留兼容性)