server

package
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2026 License: MIT Imports: 27 Imported by: 0

README

web/server 包 — HTTP 服务器与客户端

所属层级: Infrastructure Layer
设计理念: 高性能 HTTP,零外部依赖

概述

web/server 包位于 Infrastructure Layer,提供 HTTP 服务器和客户端的完整实现,使用 Go 原生 net/http 包。合并了原 net 包的服务器、路由器、中间件和 HTTP 客户端功能。

核心组件
组件 说明
HTTPServer 高性能 HTTP 服务器,支持超时配置
DefaultRouter RESTful 路由器,支持路径参数
DefaultContext HTTP 请求上下文实现
中间件 日志、恢复、请求作用域等中间件
NetClient 默认 HTTP 客户端
RetryableClient 支持重试的 HTTP 客户端
CircuitBreakerClient 带断路器的 HTTP 客户端
TLS 支持 TLS 配置和 HTTPS 客户端

HTTP 服务器

创建服务器
server := server.NewHTTPServer(
    server.WithHost(":8080"),
    server.WithReadTimeout(30*time.Second),
    server.WithWriteTimeout(30*time.Second),
)

router := server.NewRouter()
router.GET("/hello", func(ctx mvc.Context) {
    ctx.JSON(http.StatusOK, map[string]string{"message": "Hello!"})
})

server.SetHandler(router)
server.Start()
TLS 支持
tlsConfig, err := server.LoadTLSConfig("cert.pem", "key.pem")
if err != nil {
    log.Fatal(err)
}

httpsServer := server.NewHTTPServer(
    server.WithHost(":8443"),
    server.WithTLS(tlsConfig),
)

路由器

基本路由
router := server.NewRouter()

// RESTful 路由
router.GET("/users", listUsers)
router.POST("/users", createUser)
router.GET("/users/{id}", getUser)
router.PUT("/users/{id}", updateUser)
router.DELETE("/users/{id}", deleteUser)
router.PATCH("/users/{id}", patchUser)

// 路由组
api := router.Group("/api")
api.GET("/users", listUsers)

v1 := router.Group("/api/v1")
v1.GET("/users", listUsersV1)
路径参数

支持 {name} 格式的路径参数:

router.GET("/users/{id}/posts/{postId}", handler)

func handler(ctx mvc.Context) {
    id := ctx.PathParam("id")
    postId := ctx.PathParam("postId")
}

中间件

内置中间件
router := server.NewRouter()

// 日志中间件
router.Use(server.LoggingMiddleware())

// 恢复中间件(捕获 panic)
router.Use(server.RecoveryMiddleware())

// 请求作用域中间件
router.Use(server.RequestScopeMiddleware())
自定义中间件
func AuthMiddleware(next mvc.HandlerFunc) mvc.HandlerFunc {
    return func(ctx mvc.Context) {
        token := ctx.Header("Authorization")
        if token == "" {
            ctx.AbortWithStatus(http.StatusUnauthorized)
            return
        }
        next(ctx)
    }
}

router.Use(AuthMiddleware)

HTTP 客户端

基本使用
client := server.NewClient("https://api.example.com",
    server.WithClientTimeout(10*time.Second),
)

// GET 请求
resp, err := client.Get(ctx, "/users")
if err != nil {
    log.Fatal(err)
}

// POST 请求
data := map[string]any{"name": "张三", "email": "zhangsan@example.com"}
resp, err = client.Post(ctx, "/users", data)
重试客户端
client := server.NewClient("https://api.example.com")

retryableClient := server.NewRetryableClient(client,
    server.WithMaxAttempts(3),
    server.WithRetryStrategy(server.NewExponentialBackoff(
        100*time.Millisecond,
        10*time.Second,
        500, 502, 503, 504,
    )),
    server.WithOnRetry(func(attempt int, resp *server.HttpResponse, err error) {
        log.Printf("retry attempt %d", attempt)
    }),
)

resp, err := retryableClient.Get(ctx, "/users")
断路器客户端
client := server.NewClient("https://api.example.com")

circuitClient := server.NewCircuitBreakerClient(client,
    server.WithCircuitMaxFailures(5),
    server.WithCircuitResetTimeout(30*time.Second),
    server.WithFallback(func(ctx context.Context) (*server.HttpResponse, error) {
        return &server.HttpResponse{
            StatusCode: 503,
            Body:       []byte(`{"error": "service unavailable"}`),
        }, nil
    }),
)

resp, err := circuitClient.Get(ctx, "/users")
请求作用域
// 在请求作用域中存储和获取数据
func middleware(ctx mvc.Context) {
    scope := server.GetRequestScope(ctx)
    scope.Set("userID", "123")
    
    // 在后续处理中获取
    userID := scope.Get("userID").(string)
}

设计原则

  • 参考 Spring Boot:借鉴 Spring Boot 的设计理念
  • 接口实现分离:web/mvc 定义接口,web/server 提供实现
  • 零外部依赖:仅使用 Go 标准库
  • 可扩展:支持自定义中间件、客户端配置

Documentation

Overview

Package server 提供 HTTP 服务器和客户端实现。

本包包含 HTTP 请求的表单绑定功能, 仅使用 Go 标准库(无第三方依赖)。

Package server 提供 HTTP 服务器功能,用于 enhance 框架。

Package server 提供 HTTP 服务器功能,用于 enhance 框架。

Package server 提供 HTTP 服务器功能,用于 enhance 框架。

Package server 提供 HTTP 服务器功能,用于 enhance 框架。

该模块提供高性能 HTTP 服务器、路由器、中间件、HTTP 客户端、TLS 支持等网络通信功能。 参考 Spring Boot 的嵌入式服务器设计。

架构设计

  • HTTPServer: HTTP 服务器接口,定义服务器操作
  • Router: 路由器接口,负责路由注册和匹配
  • Middleware: 中间件接口,处理请求和响应
  • HTTPClient: HTTP 客户端接口,发送 HTTP 请求
  • RetryStrategy: 重试策略接口
  • CircuitBreaker: 断路器接口
  • TLSConfig: TLS 配置,支持 HTTPS

核心功能

  • HTTP 服务器: 支持高性能 HTTP 服务器
  • 路由器: 支持 RESTful 路由和注解驱动路由
  • 中间件: 支持请求拦截、日志、认证等中间件
  • HTTP 客户端: 提供简单易用的 HTTP 客户端
  • TLS 支持: 支持 HTTPS 和 TLS 配置
  • 优雅关闭: 支持服务器优雅关闭
  • 重试机制: 支持指数退避和固定延迟重试
  • 断路器: 支持熔断保护

使用方式

创建服务器:

srv := server.NewServer(":8080")
srv.GET("/api/users", userHandler)
srv.POST("/api/users", createUserHandler)

添加中间件:

srv.Use(loggingMiddleware)
srv.Use(authMiddleware)

启动服务器:

srv.Start()

TLS 配置

支持 HTTPS:

srv := server.NewServer(":8443")
srv.SetTLSConfig("/path/to/cert.pem", "/path/to/key.pem")
srv.StartTLS()

优雅关闭

支持优雅关闭:

srv.Shutdown(ctx)

Package server 提供 HTTP 服务器功能,用于 enhance 框架。

Package server 提供 HTTP 服务器功能,用于 enhance 框架。

Index

Constants

View Source
const (
	// DefaultTimeout 默认请求超时时间。
	DefaultTimeout = 30 * time.Second
)

Variables

View Source
var (
	ErrNotPointer = &BindingError{Message: "target must be a pointer"}
	ErrNotStruct  = &BindingError{Message: "target must be a struct"}
)

表单绑定的哨兵错误。

Functions

func AESDecrypt

func AESDecrypt(ciphertext, key, iv []byte) ([]byte, error)

AESDecrypt 使用 AES-CBC 模式解密数据。

参数:

  • ciphertext: 密文数据
  • key: 密钥(需与加密时一致)
  • iv: 初始向量(需与加密时一致)

返回值:

  • []byte: 明文数据
  • error: 解密错误

func AESEncrypt

func AESEncrypt(plaintext, key, iv []byte) ([]byte, error)

AESEncrypt 使用 AES-CBC 模式加密数据。

参数:

  • plaintext: 明文数据
  • key: 密钥(16/24/32 字节对应 AES-128/AES-192/AES-256)
  • iv: 初始向量(16 字节)

返回值:

  • []byte: 密文数据
  • error: 加密错误

func AESGCMDecrypt

func AESGCMDecrypt(ciphertext, key, additionalData []byte) ([]byte, error)

AESGCMDecrypt 使用 AES-GCM 模式解密数据。

参数:

  • ciphertext: nonce + 密文 + tag(AESGCMEncrypt 的输出格式)
  • key: 密钥(需与加密时一致)
  • additionalData: 附加认证数据(需与加密时一致)

返回值:

  • []byte: 明文数据
  • error: 解密错误

func AESGCMEncrypt

func AESGCMEncrypt(plaintext, key, additionalData []byte) ([]byte, error)

AESGCMEncrypt 使用 AES-GCM 模式加密数据(推荐,自带认证)。

参数:

  • plaintext: 明文数据
  • key: 密钥(16/24/32 字节)
  • additionalData: 附加认证数据(可选)

返回值:

  • []byte: nonce + 密文 + tag(拼接格式)
  • error: 加密错误

func AccessLogMiddleware

func AccessLogMiddleware(config AccessLogConfig) mvc.MiddlewareFunc

AccessLogMiddleware 创建访问日志中间件。

func CORSMiddleware

func CORSMiddleware(config CORSConfig) mvc.MiddlewareFunc

CORSMiddleware 创建 CORS 中间件。

func ErrorMiddleware

func ErrorMiddleware(config ErrorConfig) mvc.MiddlewareFunc

ErrorMiddleware 创建错误处理中间件。

func GzipMiddleware

func GzipMiddleware() mvc.MiddlewareFunc

GzipMiddleware 创建 Gzip 压缩中间件。

func InsecureTLSConfig

func InsecureTLSConfig() *tls.Config

InsecureTLSConfig 创建跳过证书验证的 TLS 配置(仅用于开发测试)。

返回值:

  • *tls.Config: 不安全但可用的 TLS 配置

func LoadCertFromPEM

func LoadCertFromPEM(certPEM, keyPEM []byte) (*tls.Config, error)

LoadCertFromPEM 从 PEM 编码的字节数据解析 TLS 证书对。

参数:

  • certPEM: PEM 格式的证书数据
  • keyPEM: PEM 格式的私钥数据

返回值:

  • *tls.Config: TLS 配置
  • error: 解析错误

func LoadClientTLSConfig

func LoadClientTLSConfig(caFile string) (*tls.Config, error)

LoadClientTLSConfig 加载仅客户端验证用的 TLS 配置(不需要服务端证书)。

参数:

  • caFile: PEM 格式的 CA 证书文件路径,用于验证服务端证书

返回值:

  • *tls.Config: TLS 配置
  • error: 加载错误

func LoadTLSConfig

func LoadTLSConfig(certFile, keyFile string) (*tls.Config, error)

LoadTLSConfig 从证书文件和密钥文件加载 TLS 配置。

参数:

  • certFile: PEM 格式的证书文件路径
  • keyFile: PEM 格式的私钥文件路径

返回值:

  • *tls.Config: TLS 配置
  • error: 加载错误

示例:

tlsCfg, err := tls.LoadTLSConfig("server.crt", "server.key")
if err != nil {
    log.Fatal(err)
}

func LoadTLSConfigWithCA

func LoadTLSConfigWithCA(certFile, keyFile, caFile string) (*tls.Config, error)

LoadTLSConfigWithCA 加载 TLS 配置并启用 CA 证书验证(用于客户端验证服务端)。

参数:

  • certFile: PEM 格式的证书文件路径
  • keyFile: PEM 格式的私钥文件路径
  • caFile: PEM 格式的 CA 证书文件路径

返回值:

  • *tls.Config: TLS 配置
  • error: 加载错误

func LoggingMiddleware

func LoggingMiddleware() mvc.MiddlewareFunc

LoggingMiddleware 创建日志中间件。

func MarshalRSAPrivateKey

func MarshalRSAPrivateKey(privateKey *rsa.PrivateKey) []byte

MarshalRSAPrivateKey 将 RSA 私钥编码为 PEM 格式。

func MarshalRSAPublicKey

func MarshalRSAPublicKey(publicKey *rsa.PublicKey) ([]byte, error)

MarshalRSAPublicKey 将 RSA 公钥编码为 PEM 格式。

func MustLoadTLSConfig

func MustLoadTLSConfig(certFile, keyFile string) *tls.Config

MustLoadTLSConfig 加载 TLS 配置,失败时 panic。

参数:

  • certFile: PEM 格式的证书文件路径
  • keyFile: PEM 格式的私钥文件路径

返回值:

  • *tls.Config: TLS 配置

func ParseRSAPrivateKey

func ParseRSAPrivateKey(pemData []byte) (*rsa.PrivateKey, error)

ParseRSAPrivateKey 从 PEM 数据解析 RSA 私钥。

func ParseRSAPublicKey

func ParseRSAPublicKey(pemData []byte) (*rsa.PublicKey, error)

ParseRSAPublicKey 从 PEM 数据解析 RSA 公钥。

func RSADecrypt

func RSADecrypt(privateKey *rsa.PrivateKey, ciphertext []byte) ([]byte, error)

RSADecrypt 使用 RSA 私钥解密数据(OAEP-SHA256)。

参数:

  • privateKey: RSA 私钥
  • ciphertext: 密文数据

返回值:

  • []byte: 明文数据
  • error: 解密错误

func RSAEncrypt

func RSAEncrypt(publicKey *rsa.PublicKey, plaintext []byte) ([]byte, error)

RSAEncrypt 使用 RSA 公钥加密数据(OAEP-SHA256)。

参数:

  • publicKey: RSA 公钥
  • plaintext: 明文数据

返回值:

  • []byte: 密文数据
  • error: 加密错误

func RSAGenerateKey

func RSAGenerateKey(bits int) (*rsa.PrivateKey, error)

RSAGenerateKey 生成 RSA 密钥对。

参数:

  • bits: 密钥位数(建议 2048 或 4096)

返回值:

  • *rsa.PrivateKey: 私钥
  • error: 生成错误

func RSASign

func RSASign(privateKey *rsa.PrivateKey, data []byte) ([]byte, error)

RSASign 使用 RSA 私钥签名数据(PKCS1v15-SHA256)。

参数:

  • privateKey: RSA 私钥
  • data: 待签名数据

返回值:

  • []byte: 签名
  • error: 签名错误

func RSAVerify

func RSAVerify(publicKey *rsa.PublicKey, data, signature []byte) error

RSAVerify 使用 RSA 公钥验证签名。

参数:

  • publicKey: RSA 公钥
  • data: 原始数据
  • signature: 签名

返回值:

  • error: 验证错误(nil 表示验证通过)

func RealIPMiddleware

func RealIPMiddleware() mvc.MiddlewareFunc

RealIPMiddleware 创建真实 IP 中间件。

func RecoveryMiddleware

func RecoveryMiddleware() mvc.MiddlewareFunc

RecoveryMiddleware 创建 panic 恢复中间件。

func RequestIDMiddleware

func RequestIDMiddleware(config RequestIDConfig) mvc.MiddlewareFunc

RequestIDMiddleware 创建请求 ID 中间件。

func RequestScopeMiddleware

func RequestScopeMiddleware(next http.Handler) http.Handler

RequestScopeMiddleware 请求级别作用域中间件

为每个 HTTP 请求创建独立的 RequestScope,并将其注入到 context 中。 请求结束时自动清理作用域中的所有 Bean 实例。

使用方式:

// 注册 RequestScope
core.RegisterScope("request", core.NewRequestScope())

// 在路由中使用中间件
handler := net.RequestScopeMiddleware(router)
http.ListenAndServe(":8080", handler)

在 Handler 中获取 RequestScope:

func handler(w http.ResponseWriter, r *http.Request) {
    scope := net.GetRequestScope(r.Context())
    if scope != nil {
        user := scope.Get("user", func() any {
            return loadUserFromDB(r)
        }).(*User)
    }
}

func RequestScopeMiddlewareFunc

func RequestScopeMiddlewareFunc() mvc.MiddlewareFunc

RequestScopeMiddlewareFunc 返回 MiddlewareFunc 版本的请求级别作用域中间件

适用于使用 enhance 中间件体系的场景。

Types

type AccessLogConfig

type AccessLogConfig struct {
	// SlowThreshold 是慢请求阈值。
	SlowThreshold time.Duration

	// Logger 是日志记录器。
	Logger *slog.Logger
}

AccessLogConfig 是访问日志中间件的配置。

func DefaultAccessLogConfig

func DefaultAccessLogConfig() AccessLogConfig

DefaultAccessLogConfig 返回默认的 AccessLog 配置。

func (AccessLogConfig) Validate

func (c AccessLogConfig) Validate() error

Validate 验证 AccessLog 配置是否有效。

type BasicAuth

type BasicAuth struct {
	Username string // 用户名
	Password string // 密码
}

BasicAuth HTTP 基本认证凭据。

type BinderOption

type BinderOption func(*FormBinder)

BinderOption 配置表单绑定器。

func WithTagName

func WithTagName(tagName string) BinderOption

WithTagName sets the struct tag name (default: "form").

type BindingError

type BindingError struct {
	Field   string
	Message string
}

BindingError 表示表单绑定错误。

func (*BindingError) Error

func (e *BindingError) Error() string

type CORSConfig

type CORSConfig struct {
	// AllowOrigins 是允许的源列表。
	AllowOrigins []string

	// AllowMethods 是允许的 HTTP 方法列表。
	AllowMethods []string

	// AllowHeaders 是允许的请求头列表。
	AllowHeaders []string

	// AllowCredentials 是否允许携带凭证。
	AllowCredentials bool

	// MaxAge 是预检请求缓存时间。
	MaxAge time.Duration
}

CORSConfig 是 CORS 中间件的配置。

func DefaultCORSConfig

func DefaultCORSConfig() CORSConfig

DefaultCORSConfig 返回默认的 CORS 配置。

func (CORSConfig) Validate

func (c CORSConfig) Validate() error

Validate 验证 CORS 配置是否有效。

type CircuitBreaker

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

CircuitBreaker 断路器。

func NewCircuitBreaker

func NewCircuitBreaker(maxFailures int, resetTimeout time.Duration) *CircuitBreaker

NewCircuitBreaker 创建断路器。

func (*CircuitBreaker) AllowRequest

func (cb *CircuitBreaker) AllowRequest() bool

AllowRequest 判断是否允许请求。

func (*CircuitBreaker) GetState

func (cb *CircuitBreaker) GetState() CircuitState

GetState 获取当前状态。

func (*CircuitBreaker) RecordFailure

func (cb *CircuitBreaker) RecordFailure()

RecordFailure 记录失败。

func (*CircuitBreaker) RecordSuccess

func (cb *CircuitBreaker) RecordSuccess()

RecordSuccess 记录成功。

type CircuitBreakerClient

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

CircuitBreakerClient 带断路器的 HTTP 客户端。

func NewCircuitBreakerClient

func NewCircuitBreakerClient(client *NetClient, opts ...CircuitBreakerOption) *CircuitBreakerClient

NewCircuitBreakerClient 创建带断路器的 HTTP 客户端。

func (*CircuitBreakerClient) Close

func (c *CircuitBreakerClient) Close() error

Close 关闭客户端。

func (*CircuitBreakerClient) Delete

func (c *CircuitBreakerClient) Delete(ctx context.Context, url string, opts ...RequestOption) (*HTTPResponse, error)

Delete 发送 DELETE 请求(带断路器保护)。

func (*CircuitBreakerClient) Get

Get 发送 GET 请求(带断路器保护)。

func (*CircuitBreakerClient) GetCircuitState

func (c *CircuitBreakerClient) GetCircuitState() CircuitState

GetCircuitState 获取断路器状态。

func (*CircuitBreakerClient) Post

func (c *CircuitBreakerClient) Post(ctx context.Context, url string, body any, opts ...RequestOption) (*HTTPResponse, error)

Post 发送 POST 请求(带断路器保护)。

func (*CircuitBreakerClient) Put

func (c *CircuitBreakerClient) Put(ctx context.Context, url string, body any, opts ...RequestOption) (*HTTPResponse, error)

Put 发送 PUT 请求(带断路器保护)。

type CircuitBreakerConfig

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

CircuitBreakerConfig 断路器配置。

type CircuitBreakerOption

type CircuitBreakerOption func(*CircuitBreakerConfig)

CircuitBreakerOption 断路器配置选项。

func WithCircuitMaxFailures

func WithCircuitMaxFailures(n int) CircuitBreakerOption

WithCircuitMaxFailures 设置最大失败次数。

func WithCircuitResetTimeout

func WithCircuitResetTimeout(d time.Duration) CircuitBreakerOption

WithCircuitResetTimeout 设置重置超时。

func WithFallback

func WithFallback(fn func(ctx context.Context) (*HTTPResponse, error)) CircuitBreakerOption

WithFallback 设置降级函数。

type CircuitState

type CircuitState int

CircuitState 断路器状态。

const (
	// CircuitClosed 关闭状态(正常请求)。
	CircuitClosed CircuitState = iota
	// CircuitOpen 打开状态(拒绝请求)。
	CircuitOpen
	// CircuitHalfOpen 半开状态(允许探测请求)。
	CircuitHalfOpen
)

type ClientMiddlewareFunc

type ClientMiddlewareFunc func(*http.Request, *HTTPResponse) error

ClientMiddlewareFunc HTTP 客户端中间件函数类型。

type ClientOption

type ClientOption func(*NetClient)

ClientOption 客户端配置选项。

func WithClientTimeout

func WithClientTimeout(timeout time.Duration) ClientOption

WithClientTimeout 设置客户端请求超时时间。

func WithHeaders

func WithHeaders(headers http.Header) ClientOption

WithHeaders 设置默认请求头。

func WithLog

func WithLog(logger log.Logger) ClientOption

WithLog 设置日志记录器。

type DefaultContext

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

DefaultContext 默认的 HTTP 上下文实现

func NewContext

func NewContext(w http.ResponseWriter, r *http.Request) *DefaultContext

NewContext 创建新的 HTTP 上下文

func (*DefaultContext) AbortWithStatus

func (c *DefaultContext) AbortWithStatus(code int)

AbortWithStatus 中止请求

func (*DefaultContext) AbortWithStatusJSON

func (c *DefaultContext) AbortWithStatusJSON(code int, body any)

AbortWithStatusJSON 中止请求并返回 JSON

func (*DefaultContext) BindJSON

func (c *DefaultContext) BindJSON(target any) error

BindJSON 解析 JSON 请求体

func (*DefaultContext) Context

func (c *DefaultContext) Context() context.Context

Context 获取请求上下文

func (*DefaultContext) Header

func (c *DefaultContext) Header(key string) string

Header 获取请求头

func (*DefaultContext) IsAborted

func (c *DefaultContext) IsAborted() bool

IsAborted 判断是否已中止

func (*DefaultContext) JSON

func (c *DefaultContext) JSON(code int, data any) error

JSON 返回 JSON 响应

func (*DefaultContext) Next

func (c *DefaultContext) Next()

Next 执行下一个中间件

func (*DefaultContext) PathParam

func (c *DefaultContext) PathParam(name string) string

PathParam 获取路径参数

func (*DefaultContext) Query

func (c *DefaultContext) Query(name string) string

Query 获取查询参数

func (*DefaultContext) QueryDefault

func (c *DefaultContext) QueryDefault(name, defaultVal string) string

QueryDefault 获取查询参数(带默认值)

func (*DefaultContext) RequestMethod

func (c *DefaultContext) RequestMethod() string

RequestMethod 返回请求方法

func (*DefaultContext) RequestURI

func (c *DefaultContext) RequestURI() string

RequestURI 返回请求 URI

func (*DefaultContext) SetContext

func (c *DefaultContext) SetContext(ctx context.Context)

SetContext 设置请求上下文

func (*DefaultContext) SetHeader

func (c *DefaultContext) SetHeader(key, value string)

SetHeader 设置响应头

func (*DefaultContext) SetStatusCode

func (c *DefaultContext) SetStatusCode(code int)

SetStatusCode 设置响应状态码

func (*DefaultContext) String

func (c *DefaultContext) String(code int, format string, args ...any)

String 返回字符串响应

func (*DefaultContext) WithMiddleware

func (c *DefaultContext) WithMiddleware(mw []mvc.MiddlewareFunc, handler mvc.HandlerFunc) *DefaultContext

WithMiddleware 设置中间件链

func (*DefaultContext) WithParams

func (c *DefaultContext) WithParams(params map[string]string) *DefaultContext

WithParams 设置路径参数

type DefaultRouter

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

DefaultRouter 默认路由器实现

func NewRouter

func NewRouter() *DefaultRouter

NewRouter 创建新的路由器

func (*DefaultRouter) DELETE

func (r *DefaultRouter) DELETE(path string, handler mvc.HandlerFunc)

DELETE 注册 DELETE 路由

func (*DefaultRouter) GET

func (r *DefaultRouter) GET(path string, handler mvc.HandlerFunc)

GET 注册 GET 路由

func (*DefaultRouter) Group

func (r *DefaultRouter) Group(prefix string) mvc.Router

Group 创建路由组

func (*DefaultRouter) PATCH

func (r *DefaultRouter) PATCH(path string, handler mvc.HandlerFunc)

PATCH 注册 PATCH 路由

func (*DefaultRouter) POST

func (r *DefaultRouter) POST(path string, handler mvc.HandlerFunc)

POST 注册 POST 路由

func (*DefaultRouter) PUT

func (r *DefaultRouter) PUT(path string, handler mvc.HandlerFunc)

PUT 注册 PUT 路由

func (*DefaultRouter) ServeHTTP

func (r *DefaultRouter) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP 实现 http.Handler 接口

func (*DefaultRouter) Use

func (r *DefaultRouter) Use(middleware mvc.MiddlewareFunc)

Use 注册中间件

type ErrorConfig

type ErrorConfig struct {
	// Logger 是日志记录器。
	Logger *slog.Logger
}

ErrorConfig 是错误处理中间件的配置。

func DefaultErrorConfig

func DefaultErrorConfig() ErrorConfig

DefaultErrorConfig 返回默认的错误配置。

func (ErrorConfig) Validate

func (c ErrorConfig) Validate() error

Validate 验证 Error 配置是否有效。

type ExponentialBackoff

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

ExponentialBackoff 指数退避重试策略。

func NewExponentialBackoff

func NewExponentialBackoff(baseDelay, maxDelay time.Duration, retryableStatus ...int) *ExponentialBackoff

NewExponentialBackoff 创建指数退避策略。

func (*ExponentialBackoff) Delay

func (e *ExponentialBackoff) Delay(attempt int) time.Duration

Delay 计算延迟时间(指数退避 + 抖动)。

func (*ExponentialBackoff) ShouldRetry

func (e *ExponentialBackoff) ShouldRetry(resp *HTTPResponse, err error, attempt int) bool

ShouldRetry 判断是否应该重试。

type FixedDelay

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

FixedDelay 固定延迟重试策略。

func NewFixedDelay

func NewFixedDelay(delay time.Duration, retryableStatus ...int) *FixedDelay

NewFixedDelay 创建固定延迟策略。

func (*FixedDelay) Delay

func (f *FixedDelay) Delay(attempt int) time.Duration

Delay 返回固定延迟。

func (*FixedDelay) ShouldRetry

func (f *FixedDelay) ShouldRetry(resp *HTTPResponse, err error, attempt int) bool

ShouldRetry 判断是否应该重试。

type FormBinder

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

FormBinder 将 HTTP 表单数据绑定到 Go 结构体。

func NewFormBinder

func NewFormBinder(opts ...BinderOption) *FormBinder

NewFormBinder 创建一个新的表单绑定器。

func (*FormBinder) Bind

func (b *FormBinder) Bind(req *http.Request, target any) error

Bind 将 HTTP 请求表单数据绑定到结构体。

func (*FormBinder) BindJSON

func (b *FormBinder) BindJSON(req *http.Request, target any) error

BindJSON 将 JSON 请求体绑定到结构体。

func (*FormBinder) BindQuery

func (b *FormBinder) BindQuery(req *http.Request, target any) error

BindQuery 将 HTTP 请求查询参数绑定到结构体。

type HTTPClient

type HTTPClient interface {
	// Get 发送 GET 请求。
	Get(ctx context.Context, url string, opts ...RequestOption) (*HTTPResponse, error)
	// Head 发送 HEAD 请求。
	Head(ctx context.Context, url string, opts ...RequestOption) (*HTTPResponse, error)
	// Post 发送 POST 请求。
	Post(ctx context.Context, url string, body any, opts ...RequestOption) (*HTTPResponse, error)
	// Put 发送 PUT 请求。
	Put(ctx context.Context, url string, body any, opts ...RequestOption) (*HTTPResponse, error)
	// Patch 发送 PATCH 请求。
	Patch(ctx context.Context, url string, body any, opts ...RequestOption) (*HTTPResponse, error)
	// Delete 发送 DELETE 请求。
	Delete(ctx context.Context, url string, opts ...RequestOption) (*HTTPResponse, error)
	// Options 发送 OPTIONS 请求。
	Options(ctx context.Context, url string, opts ...RequestOption) (*HTTPResponse, error)
	// Do 发送自定义 HTTP 请求。
	Do(ctx context.Context, req any) (*HTTPResponse, error)
	// Close 关闭客户端并释放资源。
	Close() error
}

HTTPClient HTTP 客户端接口。

提供统一的 HTTP 请求发送接口。

type HTTPClientBuilder

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

HTTPClientBuilder HTTP 客户端构建器,支持链式配置

func NewHTTPClientBuilder

func NewHTTPClientBuilder() *HTTPClientBuilder

NewHTTPClientBuilder 创建 HTTP 客户端构建器

func (*HTTPClientBuilder) BaseURL

func (b *HTTPClientBuilder) BaseURL(url string) *HTTPClientBuilder

BaseURL 设置基础 URL

func (*HTTPClientBuilder) Build

func (b *HTTPClientBuilder) Build() (HTTPClient, error)

Build 构建 HTTP 客户端

func (*HTTPClientBuilder) Header

func (b *HTTPClientBuilder) Header(key, value string) *HTTPClientBuilder

Header 添加默认请求头

func (*HTTPClientBuilder) Middleware

Middleware 添加客户端中间件

func (*HTTPClientBuilder) MustBuild

func (b *HTTPClientBuilder) MustBuild() HTTPClient

MustBuild 构建 HTTP 客户端,失败则 panic

func (*HTTPClientBuilder) Retry

func (b *HTTPClientBuilder) Retry(opts ...RetryOption) *HTTPClientBuilder

Retry 配置重试策略

func (*HTTPClientBuilder) Timeout

func (b *HTTPClientBuilder) Timeout(timeout time.Duration) *HTTPClientBuilder

Timeout 设置请求超时时间

type HTTPRequest

type HTTPRequest struct {
	Header      http.Header   // 请求头
	Query       url.Values    // 查询参数
	Timeout     time.Duration // 请求超时
	AuthToken   string        // Bearer 认证令牌
	ContentType string        // 请求 Content-Type
	BasicAuth   BasicAuth     // 基本认证凭据
}

HTTPRequest HTTP 请求封装。

type HTTPResponse

type HTTPResponse struct {
	StatusCode int         // HTTP 状态码
	Header     http.Header // 响应头
	Body       []byte      // 响应体
}

HTTPResponse HTTP 响应封装。

func (*HTTPResponse) Bind

func (r *HTTPResponse) Bind(v any) error

Bind 绑定响应体到目标结构体。

func (*HTTPResponse) IsClientError

func (r *HTTPResponse) IsClientError() bool

IsClientError 判断响应是否为客户端错误状态码 (4xx)。

func (*HTTPResponse) IsRedirect

func (r *HTTPResponse) IsRedirect() bool

IsRedirect 判断响应是否为重定向状态码 (3xx)。

func (*HTTPResponse) IsServerError

func (r *HTTPResponse) IsServerError() bool

IsServerError 判断响应是否为服务端错误状态码 (5xx)。

func (*HTTPResponse) IsSuccess

func (r *HTTPResponse) IsSuccess() bool

IsSuccess 判断响应是否为成功状态码 (2xx)。

func (*HTTPResponse) String

func (r *HTTPResponse) String() string

String 获取响应体字符串。

func (*HTTPResponse) Unmarshal

func (r *HTTPResponse) Unmarshal(target any) error

Unmarshal 反序列化 JSON 数据到指定目标。

参数:

  • target: 指向目标结构体的指针

返回:

  • error: 反序列化错误

type HTTPServer

type HTTPServer interface {
	// Start 启动 HTTP 服务器并开始监听请求。
	Start() error
	// Stop 优雅地停止服务器,等待正在处理的请求完成。
	Stop(ctx context.Context) error
	// SetHandler 设置自定义的 HTTP 处理器。
	SetHandler(handler http.Handler)
	// Use 向服务器注册一个中间件。
	Use(middleware func(http.Handler) http.Handler)
}

HTTPServer HTTP 服务器接口。

定义 HTTP 服务器的生命周期管理。

type HTTPServerBuilder

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

HTTPServerBuilder HTTP 服务器构建器,支持链式配置

func NewHTTPServerBuilder

func NewHTTPServerBuilder() *HTTPServerBuilder

NewHTTPServerBuilder 创建 HTTP 服务器构建器

func (*HTTPServerBuilder) Build

func (b *HTTPServerBuilder) Build() (*HttpServer, error)

Build 构建 HTTP 服务器

func (*HTTPServerBuilder) Handler

func (b *HTTPServerBuilder) Handler(handler http.Handler) *HTTPServerBuilder

Handler 设置 HTTP 处理器

func (*HTTPServerBuilder) Host

Host 设置监听地址

func (*HTTPServerBuilder) IdleTimeout

func (b *HTTPServerBuilder) IdleTimeout(timeout time.Duration) *HTTPServerBuilder

IdleTimeout 设置空闲超时

func (*HTTPServerBuilder) Middleware

func (b *HTTPServerBuilder) Middleware(middleware func(http.Handler) http.Handler) *HTTPServerBuilder

Middleware 添加中间件

func (*HTTPServerBuilder) MustBuild

func (b *HTTPServerBuilder) MustBuild() *HttpServer

MustBuild 构建 HTTP 服务器,失败则 panic

func (*HTTPServerBuilder) ReadTimeout

func (b *HTTPServerBuilder) ReadTimeout(timeout time.Duration) *HTTPServerBuilder

ReadTimeout 设置读取超时

func (*HTTPServerBuilder) TLS

func (b *HTTPServerBuilder) TLS(certFile, keyFile string) *HTTPServerBuilder

TLS 设置 TLS 证书

func (*HTTPServerBuilder) WriteTimeout

func (b *HTTPServerBuilder) WriteTimeout(timeout time.Duration) *HTTPServerBuilder

WriteTimeout 设置写入超时

type HttpServer

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

HttpServer 是基于 net/http 原生包的 Server 接口实现。

func NewHTTPServer

func NewHTTPServer(opts ...ServerOption) *HttpServer

NewHTTPServer 创建一个新的基于 net/http 的 HTTP 服务器。

func (*HttpServer) SetHandler

func (s *HttpServer) SetHandler(handler http.Handler)

SetHandler 设置自定义的 HTTP 处理器。

func (*HttpServer) Start

func (s *HttpServer) Start() error

Start 启动 HTTP 服务器并开始监听请求。

func (*HttpServer) StartH2C

func (s *HttpServer) StartH2C() error

StartH2C 启动 HTTP/2 明文支持(不需要 TLS)。

func (*HttpServer) StartTLS

func (s *HttpServer) StartTLS(certFile, keyFile string) error

StartTLS 启动带 TLS 的 HTTP 服务器(支持 HTTP/2)。

func (*HttpServer) Stop

func (s *HttpServer) Stop(ctx context.Context) error

Stop 优雅地停止服务器,等待正在处理的请求完成。

func (*HttpServer) Use

func (s *HttpServer) Use(middleware func(http.Handler) http.Handler)

Use 向服务器注册一个中间件。

type HttpServerAdapter

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

HttpServerAdapter 将 web/server.HttpServer 适配到 mvc.Server 接口 这样可以让 HttpServer 与 mvc.WebStarter 配合使用

func NewHttpServerAdapter

func NewHttpServerAdapter(opts ...ServerOption) *HttpServerAdapter

NewHttpServerAdapter 创建一个新的 HTTP 服务器适配器

func (*HttpServerAdapter) GetServer

func (a *HttpServerAdapter) GetServer() *HttpServer

GetServer 获取底层的 HttpServer 实例

func (*HttpServerAdapter) SetHandler

func (a *HttpServerAdapter) SetHandler(handler any)

SetHandler 设置自定义的 HTTP 处理器

func (*HttpServerAdapter) Start

func (a *HttpServerAdapter) Start() error

Start 启动 HTTP 服务器

func (*HttpServerAdapter) Stop

func (a *HttpServerAdapter) Stop(ctx context.Context) error

Stop 优雅地停止服务器

func (*HttpServerAdapter) Use

func (a *HttpServerAdapter) Use(m any)

Use 向服务器注册一个中间件

type NetClient

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

NetClient HTTP 客户端实现。

func NewClient

func NewClient(baseURL string, opts ...ClientOption) *NetClient

NewClient 创建新的客户端。

func NewTLSClient

func NewTLSClient(baseURL string, opts ...TLSClientOption) *NetClient

NewTLSClient 创建 HTTPS 客户端构建器。

参数:

返回值:

  • *NetClient: 配置好的 HTTPS 客户端实例

func (*NetClient) Close

func (c *NetClient) Close() error

Close 关闭客户端。

func (*NetClient) Delete

func (c *NetClient) Delete(ctx context.Context, path string, opts ...RequestOption) (*HTTPResponse, error)

Delete 发送 DELETE 请求。

func (*NetClient) Do

func (c *NetClient) Do(ctx context.Context, request any) (*HTTPResponse, error)

Do 执行自定义 HTTP 请求并返回响应。

func (*NetClient) Get

func (c *NetClient) Get(ctx context.Context, path string, opts ...RequestOption) (*HTTPResponse, error)

Get 发送 GET 请求。

func (*NetClient) Head

func (c *NetClient) Head(ctx context.Context, path string, opts ...RequestOption) (*HTTPResponse, error)

Head 发送 HEAD 请求。

func (*NetClient) Options

func (c *NetClient) Options(ctx context.Context, path string, opts ...RequestOption) (*HTTPResponse, error)

Options 发送 OPTIONS 请求。

func (*NetClient) Patch

func (c *NetClient) Patch(ctx context.Context, path string, body any, opts ...RequestOption) (*HTTPResponse, error)

Patch 发送 PATCH 请求。

func (*NetClient) Post

func (c *NetClient) Post(ctx context.Context, path string, body any, opts ...RequestOption) (*HTTPResponse, error)

Post 发送 POST 请求。

func (*NetClient) Put

func (c *NetClient) Put(ctx context.Context, path string, body any, opts ...RequestOption) (*HTTPResponse, error)

Put 发送 PUT 请求。

func (*NetClient) WithMiddleware

func (c *NetClient) WithMiddleware(m ClientMiddlewareFunc) *NetClient

WithMiddleware 添加中间件。

type RequestBuilder

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

RequestBuilder 请求构建器,简化 HTTP 请求构建

func NewRequestBuilder

func NewRequestBuilder(ctx context.Context, method, path string) *RequestBuilder

NewRequestBuilder 创建请求构建器

func (*RequestBuilder) AuthToken

func (b *RequestBuilder) AuthToken(token string) *RequestBuilder

AuthToken 设置认证令牌

func (*RequestBuilder) Body

func (b *RequestBuilder) Body(body any) *RequestBuilder

Body 设置请求体

func (*RequestBuilder) Build

func (b *RequestBuilder) Build() []RequestOption

Build 构建请求选项

func (*RequestBuilder) ContentType

func (b *RequestBuilder) ContentType(contentType string) *RequestBuilder

ContentType 设置 Content-Type

func (*RequestBuilder) Execute

func (b *RequestBuilder) Execute(client HTTPClient) (*HTTPResponse, error)

Execute 执行请求

func (*RequestBuilder) Header

func (b *RequestBuilder) Header(key, value string) *RequestBuilder

Header 添加请求头

func (*RequestBuilder) Query

func (b *RequestBuilder) Query(key, value string) *RequestBuilder

Query 添加查询参数

func (*RequestBuilder) Timeout

func (b *RequestBuilder) Timeout(timeout time.Duration) *RequestBuilder

Timeout 设置请求超时

type RequestIDConfig

type RequestIDConfig struct {
	// HeaderName 是用于存储请求 ID 的请求头名称。
	HeaderName string

	// Generator 是请求 ID 生成函数。
	Generator func() string
}

RequestIDConfig 是 RequestID 中间件的配置。

func DefaultRequestIDConfig

func DefaultRequestIDConfig() RequestIDConfig

DefaultRequestIDConfig 返回默认的 RequestID 配置。

func (RequestIDConfig) Validate

func (c RequestIDConfig) Validate() error

Validate 验证 RequestID 配置是否有效。

type RequestOption

type RequestOption func(*HTTPRequest)

RequestOption 请求选项配置函数。

func WithAuthToken

func WithAuthToken(token string) RequestOption

WithAuthToken 设置认证令牌。

func WithBasicAuth

func WithBasicAuth(username, password string) RequestOption

WithBasicAuth 设置基本认证。

func WithContentType

func WithContentType(contentType string) RequestOption

WithContentType 设置请求 Content-Type。

func WithHeader

func WithHeader(key, value string) RequestOption

WithHeader 设置请求头。

func WithQuery

func WithQuery(key, value string) RequestOption

WithQuery 设置查询参数。

func WithTimeout

func WithTimeout(timeout time.Duration) RequestOption

WithTimeout 设置请求超时。

type RequestScope

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

RequestScope 请求级别作用域

为每个 HTTP 请求创建独立的作用域,用于管理请求生命周期内的 Bean 实例。 请求结束时自动清理所有 Bean 实例。

func GetRequestScope

func GetRequestScope(ctx context.Context) *RequestScope

GetRequestScope 从 context 中获取 RequestScope

如果 context 中没有 RequestScope,返回 nil。

func MustGetRequestScope

func MustGetRequestScope(ctx context.Context) *RequestScope

MustGetRequestScope 从 context 中获取 RequestScope,不存在时 panic

func NewRequestScope

func NewRequestScope() *RequestScope

NewRequestScope 创建新的请求级别作用域

func (*RequestScope) Clear

func (s *RequestScope) Clear()

Clear 清理作用域中的所有 Bean 实例

func (*RequestScope) Get

func (s *RequestScope) Get(name string, factory func() any) any

Get 获取或创建指定名称的 Bean 实例

如果缓存中已存在该 Bean,直接返回;否则调用 factory 创建并缓存。

func (*RequestScope) Set

func (s *RequestScope) Set(name string, bean any)

Set 设置 Bean 实例

type RetryConfig

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

RetryConfig 重试配置。

type RetryOption

type RetryOption func(*RetryConfig)

RetryOption 重试配置选项。

func WithMaxAttempts

func WithMaxAttempts(n int) RetryOption

WithMaxAttempts 设置最大重试次数。

func WithOnRetry

func WithOnRetry(fn func(attempt int, resp *HTTPResponse, err error)) RetryOption

WithOnRetry 设置重试回调。

func WithRetryStrategy

func WithRetryStrategy(strategy RetryStrategy) RetryOption

WithRetryStrategy 设置重试策略。

type RetryStrategy

type RetryStrategy interface {
	// ShouldRetry 判断是否应该重试。
	ShouldRetry(resp *HTTPResponse, err error, attempt int) bool
	// Delay 计算下次重试的延迟时间。
	Delay(attempt int) time.Duration
}

RetryStrategy 重试策略接口。

type RetryableClient

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

RetryableClient 支持重试的 HTTP 客户端。

func NewRetryableClient

func NewRetryableClient(client *NetClient, opts ...RetryOption) *RetryableClient

NewRetryableClient 创建可重试的 HTTP 客户端。

func (*RetryableClient) Close

func (c *RetryableClient) Close() error

Close 关闭客户端。

func (*RetryableClient) Delete

func (c *RetryableClient) Delete(ctx context.Context, url string, opts ...RequestOption) (*HTTPResponse, error)

Delete 发送 DELETE 请求(支持重试)。

func (*RetryableClient) Do

func (c *RetryableClient) Do(ctx context.Context, req any) (*HTTPResponse, error)

Do 执行自定义请求(支持重试)。

func (*RetryableClient) Get

func (c *RetryableClient) Get(ctx context.Context, url string, opts ...RequestOption) (*HTTPResponse, error)

Get 发送 GET 请求(支持重试)。

func (*RetryableClient) Head

func (c *RetryableClient) Head(ctx context.Context, url string, opts ...RequestOption) (*HTTPResponse, error)

Head 发送 HEAD 请求(支持重试)。

func (*RetryableClient) Options

func (c *RetryableClient) Options(ctx context.Context, url string, opts ...RequestOption) (*HTTPResponse, error)

Options 发送 OPTIONS 请求(支持重试)。

func (*RetryableClient) Patch

func (c *RetryableClient) Patch(ctx context.Context, url string, body any, opts ...RequestOption) (*HTTPResponse, error)

Patch 发送 PATCH 请求(支持重试)。

func (*RetryableClient) Post

func (c *RetryableClient) Post(ctx context.Context, url string, body any, opts ...RequestOption) (*HTTPResponse, error)

Post 发送 POST 请求(支持重试)。

func (*RetryableClient) Put

func (c *RetryableClient) Put(ctx context.Context, url string, body any, opts ...RequestOption) (*HTTPResponse, error)

Put 发送 PUT 请求(支持重试)。

type Router

type Router interface {
	// GET 注册 GET 路由。
	GET(path string, handler http.HandlerFunc)
	// POST 注册 POST 路由。
	POST(path string, handler http.HandlerFunc)
	// PUT 注册 PUT 路由。
	PUT(path string, handler http.HandlerFunc)
	// DELETE 注册 DELETE 路由。
	DELETE(path string, handler http.HandlerFunc)
	// PATCH 注册 PATCH 路由。
	PATCH(path string, handler http.HandlerFunc)
	// Group 创建路由组。
	Group(prefix string) Router
	// Use 注册中间件。
	Use(middleware func(http.Handler) http.Handler)
	// ServeHTTP 实现 http.Handler 接口。
	ServeHTTP(w http.ResponseWriter, r *http.Request)
}

Router 路由器接口。

提供路由注册和路由组功能。

type ScopeContextKey

type ScopeContextKey struct{}

ScopeContextKey 是 RequestScope 在 context 中的键

type ServerOption

type ServerOption func(*HttpServer)

ServerOption 是服务器配置选项函数。

func WithHTTP2

func WithHTTP2(enabled bool) ServerOption

WithHTTP2 启用 HTTP/2 支持(需要 TLS)。

func WithHost

func WithHost(host string) ServerOption

WithHost 设置服务器监听地址。

func WithIdleTimeout

func WithIdleTimeout(timeout time.Duration) ServerOption

WithIdleTimeout 设置空闲超时。

func WithLogger

func WithLogger(logger log.Logger) ServerOption

WithLogger 设置日志记录器。

func WithReadTimeout

func WithReadTimeout(timeout time.Duration) ServerOption

WithReadTimeout 设置读取超时。

func WithTLS

func WithTLS(certFile, keyFile string) ServerOption

WithTLS 设置 TLS 证书和密钥文件路径。

func WithWriteTimeout

func WithWriteTimeout(timeout time.Duration) ServerOption

WithWriteTimeout 设置写入超时。

type TLSClientBuilder

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

TLSClientBuilder 是 HTTPS 客户端构建器,封装 NetClient 并配置 TLS。

type TLSClientOption

type TLSClientOption func(*TLSClientBuilder)

TLSClientOption 是 HTTPS 客户端配置选项。

func WithInsecureTLS

func WithInsecureTLS() TLSClientOption

WithInsecureTLS 跳过 TLS 证书验证(仅用于开发测试)。

func WithTLSConfig

func WithTLSConfig(tlsConfig *tls.Config) TLSClientOption

WithTLSConfig 设置 TLS 配置。

func WithTLSDefaultHeader

func WithTLSDefaultHeader(key, value string) TLSClientOption

WithTLSDefaultHeader 设置默认请求头。

func WithTLSRequestTimeout

func WithTLSRequestTimeout(timeout time.Duration) TLSClientOption

WithTLSRequestTimeout 设置请求超时时间。

func WithTLSTransport

func WithTLSTransport(transport *http.Transport) TLSClientOption

WithTLSTransport 设置自定义 HTTP Transport。

Jump to

Keyboard shortcuts

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