httpclient

package
v1.60.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package httpclient 提供通用 HTTP 请求工具(零依赖 net/http): GET/POST/PUT/DELETE,支持 query 参数、表单、JSON、原始 body、自定义 header。 与 framework/thirdparty 的区别:thirdparty 面向签名对接,本包面向通用 HTTP 调用。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetGlobal

func SetGlobal(client *Client)

SetGlobal 设置全局客户端(New 成功后自动调用)。

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client HTTP 客户端(并发安全)。

func Get

func Get() *Client

Get 获取全局 HTTP 客户端;未初始化返回 nil。

func New

func New(config Config) *Client

New 创建客户端。

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, path string, options Options, out interface{}) (*Response, error)

Delete DELETE 请求。

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string, options Options, out interface{}) (*Response, error)

Get GET 请求;out 非 nil 时自动 JSON 解码到 out。

func (*Client) Post

func (c *Client) Post(ctx context.Context, path string, options Options, out interface{}) (*Response, error)

Post POST 请求。

func (*Client) Put

func (c *Client) Put(ctx context.Context, path string, options Options, out interface{}) (*Response, error)

Put PUT 请求。

type Config

type Config struct {
	// BaseURL 基础地址(可选,path 为绝对 URL 时忽略)。
	BaseURL string
	// Timeout 请求超时(默认 10s)。
	Timeout time.Duration
	// DefaultHeaders 默认请求头(每个请求都带,可被 Options.Headers 覆盖)。
	DefaultHeaders map[string]string
	// MaxRetries 网络错误重试次数(默认 0 不重试)。
	MaxRetries int
}

Config 客户端配置。

type Options

type Options struct {
	// Query 查询参数(URL 编码拼接)。
	Query map[string]string
	// Headers 请求头(合并 DefaultHeaders,同名覆盖)。
	Headers map[string]string
	// Form 表单参数(application/x-www-form-urlencoded)。
	Form map[string]string
	// JSON 对象(application/json 序列化)。
	JSON interface{}
	// Body 原始请求体(与 ContentType 配合;优先级高于 Form/JSON)。
	Body []byte
	// ContentType 请求体类型(如 text/plain、application/xml)。
	ContentType string
}

Options 单次请求选项。

type Response

type Response struct {
	StatusCode int
	Headers    http.Header
	Body       []byte
}

Response 响应。

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess 2xx 判断。

func (*Response) Text

func (r *Response) Text() string

Text 响应体文本。

func (*Response) Unmarshal

func (r *Response) Unmarshal(out interface{}) error

Unmarshal 响应体解析为 JSON(目标对象)。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL