Documentation
¶
Overview ¶
Package requests 提供了增强的HTTP响应写入器 Package requests provides enhanced HTTP response writer
Package requests 提供了HTTP客户端的中间件设置功能 Package requests provides middleware setup functionality for HTTP client
Package requests 提供了HTTP请求统计和性能监控功能 Package requests provides HTTP request statistics and performance monitoring
Package requests 提供了HTTP请求追踪和调试功能 Package requests provides HTTP request tracing and debugging functionality
Package requests 提供了唯一ID生成功能 Package requests provides unique ID generation functionality
Package requests 提供了HTTP服务器中间件,包括SSE、CORS等功能 Package requests provides HTTP server middleware including SSE, CORS, etc.
Package requests 提供了HTTP客户端和服务器的工具函数 Package requests provides utility functions for HTTP client and server
Index ¶
- Constants
- Variables
- func CORS() func(next http.Handler) http.Handler
- func CopyBody(b io.ReadCloser) (*bytes.Buffer, io.ReadCloser, error)
- func Delete(url, contentType string, body io.Reader) (*http.Response, error)
- func GenId(id ...string) string
- func Get(url string) (*http.Response, error)
- func Head(url string) (resp *http.Response, err error)
- func ListenAndServe(ctx context.Context, h http.Handler, opts ...Option) error
- func Log(format string, v ...any)
- func LogS(ctx context.Context, stat *Stat)
- func NewRequestWithContext(ctx context.Context, options Options) (*http.Request, error)
- func ParseBody(r io.ReadCloser) (*bytes.Buffer, error)
- func Post(url string, contentType string, body io.Reader) (*http.Response, error)
- func PostForm(url string, data url.Values) (*http.Response, error)
- func Put(url, contentType string, body io.Reader) (*http.Response, error)
- func SSE() func(next http.Handler) http.Handler
- func Socket(ctx context.Context, opts ...Option) (net.Conn, error)
- func WarpHandler(next http.Handler) func(http.Handler) http.Handler
- func WarpRoundTripper(next http.RoundTripper) func(http.RoundTripper) http.RoundTripper
- type Node
- type Option
- func BasicAuth(username, password string) Option
- func Body(body any) Option
- func CertKey(cert, key string) Option
- func Cookie(cookie http.Cookie) Option
- func Cookies(cookies ...http.Cookie) Option
- func Form(form url.Values) Option
- func Gzip(body any) Option
- func Header(k, v string) Option
- func Headers(kv map[string]string) Option
- func Host(host string) Option
- func LocalAddr(addr net.Addr) Option
- func Logf(f func(context.Context, *Stat)) Option
- func MaxConns(conn int) Option
- func Method(method string) Option
- func OnShutdown(f func(*http.Server)) Option
- func OnStart(f func(*http.Server)) Option
- func Param(k string, v ...string) Option
- func Params(query map[string]string) Option
- func Path(path string) Option
- func Proxy(addr string) Option
- func RoundTripper(tr http.RoundTripper) Option
- func Setup(fn ...func(tripper http.RoundTripper) http.RoundTripper) Option
- func Stream(stream func(int64, []byte) error) Option
- func Timeout(timeout time.Duration) Option
- func Trace(mLimit ...int) Option
- func URL(url string) Option
- func Use(fn ...func(http.Handler) http.Handler) Option
- func Verify(verify bool) Option
- type Options
- type ParamNode
- type Response
- type ResponseWriter
- func (w *ResponseWriter) Flush()
- func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (w *ResponseWriter) Push(target string, opts *http.PushOptions) error
- func (w *ResponseWriter) Read(b []byte) (int, error)
- func (w *ResponseWriter) Write(b []byte) (int, error)
- func (w *ResponseWriter) WriteHeader(statusCode int)
- type RoundTripperFunc
- type ServeMux
- func (mux *ServeMux) CONNECT(path string, v any, opts ...Option)
- func (mux *ServeMux) DELETE(path string, v any, opts ...Option)
- func (mux *ServeMux) GET(path string, v any, opts ...Option)
- func (mux *ServeMux) HEAD(path string, v any, opts ...Option)
- func (mux *ServeMux) Handle(path string, h http.Handler, opts ...Option)
- func (mux *ServeMux) HandleFunc(path string, f func(http.ResponseWriter, *http.Request), opts ...Option)
- func (mux *ServeMux) OPTIONS(path string, v any, opts ...Option)
- func (mux *ServeMux) POST(path string, v any, opts ...Option)
- func (mux *ServeMux) PUT(path string, v any, opts ...Option)
- func (mux *ServeMux) Pprof()
- func (mux *ServeMux) Print(w io.Writer)
- func (mux *ServeMux) Redirect(source, target string)
- func (mux *ServeMux) Route(path string, v any, opts ...Option)
- func (mux *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (mux *ServeMux) TRACE(path string, v any, opts ...Option)
- func (mux *ServeMux) Use(fn ...func(http.Handler) http.Handler)
- type Server
- type ServerSentEvents
- func (s *ServerSentEvents) End()
- func (s *ServerSentEvents) Header() http.Header
- func (s *ServerSentEvents) Read(b []byte) ([]byte, error)
- func (s *ServerSentEvents) Send(name string, b []byte) (int, error)
- func (s *ServerSentEvents) Write(b []byte) (int, error)
- func (s *ServerSentEvents) WriteHeader(statusCode int)
- type Session
- func (s *Session) Do(ctx context.Context, opts ...Option) (*http.Response, error)
- func (s *Session) DoRequest(ctx context.Context, opts ...Option) (*Response, error)
- func (s *Session) HTTPClient(opts ...Option) *http.Client
- func (s *Session) RoundTrip(r *http.Request) (*http.Response, error)
- func (s *Session) RoundTripper(opts ...Option) http.RoundTripper
- func (s *Session) Transport() *http.Transport
- type Stat
Constants ¶
const RequestId = "Request-Id"
RequestId 是用于跟踪请求的HTTP头字段名称 RequestId is the HTTP header field name used for request tracking
Variables ¶
var ( MethodGet = Method("GET") // GET 方法 / GET method MethodPost = Method("POST") // POST 方法 / POST method )
预定义的常用 HTTP 方法 Pre-defined common HTTP methods
var ErrHandler = func(err string, code int) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, err, code) }) }
ErrHandler 是默认的错误处理器,返回一个简单的错误响应 ErrHandler is the default error handler that returns a simple error response
参数 / Parameters:
- err: 错误消息 / Error message
- code: HTTP 状态码 / HTTP status code
返回值 / Returns:
- http.Handler: 错误处理器 / Error handler
Functions ¶
func CORS ¶
CORS 返回一个跨域资源共享(Cross-Origin Resource Sharing)中间件 该中间件允许来自任何源的跨域请求,并处理预检请求
CORS returns a Cross-Origin Resource Sharing middleware This middleware allows cross-origin requests from any origin and handles preflight requests
返回值 / Returns:
- func(next http.Handler) http.Handler: HTTP中间件函数 / HTTP middleware function
CORS配置 / CORS Configuration:
- Access-Control-Allow-Origin: * (允许所有源) / * (allows all origins)
- Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
- Access-Control-Allow-Headers: Content-Type, Authorization
预检请求处理 / Preflight Request Handling:
- 自动响应OPTIONS请求 / Automatically responds to OPTIONS requests
- 返回204 No Content状态码 / Returns 204 No Content status code
使用场景 / Use Cases:
- 允许前端跨域访问API / Allow frontend cross-origin API access
- 公共API服务 / Public API services
- 微服务间通信 / Inter-microservice communication
示例 / Example:
mux := requests.NewServeMux()
mux.Use(requests.CORS())
mux.GET("/api/data", handler)
func CopyBody ¶
func CopyBody(b io.ReadCloser) (*bytes.Buffer, io.ReadCloser, error)
CopyBody 将ReadCloser的所有内容读取到内存,然后返回两个等价的ReadCloser 两个返回的ReadCloser都能读取相同的字节内容
CopyBody reads all of b to memory and then returns two equivalent ReadClosers yielding the same bytes.
参数 / Parameters:
- b: io.ReadCloser - 需要复制的原始body / The original body to copy
返回值 / Returns:
- *bytes.Buffer: 包含body内容的缓冲区 / Buffer containing the body content
- io.ReadCloser: 可以重新读取body内容的ReadCloser / ReadCloser that can read the body content again
- error: 读取失败时的错误 / Error if reading fails
注意事项 / Notes:
- 如果初始读取所有字节失败,则返回错误 / Returns error if the initial slurp of all bytes fails
- 不保证返回的ReadCloser具有相同的错误匹配行为 / Does not guarantee identical error-matching behavior
- 主要用于需要多次读取body的场景 / Mainly used for scenarios requiring multiple reads of the body
使用场景 / Use Cases:
- 中间件需要检查请求体但不能消耗它 / Middleware needs to inspect request body without consuming it
- 需要记录请求体同时还要转发给下一个处理器 / Need to log request body while forwarding to next handler
- 实现请求重试功能时保留原始请求体 / Preserve original request body for retry functionality
示例 / Example:
// 复制请求体以便多次使用
// Copy request body for multiple uses
buf, bodyReader, err := requests.CopyBody(req.Body)
if err != nil {
log.Fatal(err)
}
// 可以从buf读取内容 / Can read content from buf
fmt.Printf("Body: %s\n", buf.String())
// 可以将bodyReader赋值回req.Body / Can assign bodyReader back to req.Body
req.Body = bodyReader
func Delete ¶
Delete 发送 DELETE 请求 Delete sends a DELETE request
参数 / Parameters:
- url: 请求的URL地址 / The URL to request
- contentType: 内容类型 / Content type
- body: 请求体数据 / Request body data
返回值 / Returns:
- *http.Response: HTTP响应对象 / HTTP response object
- error: 请求过程中的错误 / Error during the request
func GenId ¶
GenId 生成唯一的随机ID(使用Base36编码) 如果提供了id参数且非空,则直接返回该id 否则基于当前纳秒时间戳和随机数生成唯一ID
GenId generates a unique random ID (using Base36 encoding) If an id parameter is provided and not empty, returns that id directly Otherwise generates a unique ID based on current nanosecond timestamp and random number
参数 / Parameters:
- id: ...string - 可选的自定义ID(如果提供且非空,则直接使用) / Optional custom ID (if provided and not empty, use directly)
返回值 / Returns:
- string: 生成的唯一ID(大写Base36格式) / Generated unique ID (uppercase Base36 format)
ID生成算法 / ID Generation Algorithm:
- 使用纳秒级时间戳 * 1000 + 随机数(0-999) / Uses nanosecond timestamp * 1000 + random(0-999)
- 转换为Base36编码(0-9, A-Z) / Converts to Base36 encoding (0-9, A-Z)
- 结果转换为大写字母 / Result converted to uppercase
使用场景 / Use Cases:
- 生成请求唯一标识符(Request-Id) / Generate unique request identifiers (Request-Id)
- 分布式系统追踪 / Distributed system tracing
- 日志关联 / Log correlation
- 事务ID生成 / Transaction ID generation
示例 / Example:
// 生成随机ID
// Generate random ID
id := requests.GenId()
fmt.Printf("Generated ID: %s\n", id) // 例如:2F8K3L9M4N7P
// 使用自定义ID
// Use custom ID
customId := requests.GenId("my-custom-id")
fmt.Printf("Custom ID: %s\n", customId) // 输出:my-custom-id
// 在请求中使用
// Use in requests
resp, _ := session.DoRequest(ctx,
requests.URL("http://example.com"),
requests.Header("Request-Id", requests.GenId()),
)
func Get ¶
Get 发送 GET 请求 这是一个便捷方法,完全兼容 net/http 包的使用方式 Get sends a GET request This is a convenience method, fully compatible with the net/http package usage
参数 / Parameters:
- url: 请求的URL地址 / The URL to request
返回值 / Returns:
- *http.Response: HTTP响应对象,注意:必须手动关闭 resp.Body / HTTP response object, note: resp.Body must be closed manually
- error: 请求过程中的错误 / Error during the request
示例 / Example:
resp, err := requests.Get("https://api.example.com/users")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
func Head ¶
Head 发送 HEAD 请求 Head sends a HEAD request
参数 / Parameters:
- url: 请求的URL地址 / The URL to request
返回值 / Returns:
- resp: HTTP响应对象 / HTTP response object
- err: 请求过程中的错误 / Error during the request
func ListenAndServe ¶
ListenAndServe 是一个便捷函数,创建服务器并启动监听 ListenAndServe is a convenience function that creates a server and starts listening
参数 / Parameters:
- ctx: 上下文(用于优雅关闭)/ Context (for graceful shutdown)
- h: HTTP 处理器 / HTTP handler
- opts: 配置选项 / Configuration options
返回值 / Returns:
- error: 服务器错误 / Server error
说明 / Notes:
- 这是一个阻塞调用,会一直运行直到服务器关闭
- This is a blocking call that runs until server shutdown
- 当 ctx 被取消时,服务器会优雅关闭
- Server shuts down gracefully when ctx is cancelled
示例 / Example:
// 简单服务器
// Simple server
mux := requests.NewServeMux()
mux.Route("/", homeHandler)
err := requests.ListenAndServe(
context.Background(),
mux,
requests.URL("0.0.0.0:8080"),
)
// 带优雅关闭的服务器
// Server with graceful shutdown
ctx, cancel := context.WithCancel(context.Background())
go func() {
<-sigint // 等待中断信号 / Wait for interrupt signal
cancel() // 触发优雅关闭 / Trigger graceful shutdown
}()
requests.ListenAndServe(ctx, mux, requests.URL("0.0.0.0:8080"))
func Log ¶
Log 打印日志信息(用于调试追踪) 格式化输出字符串并添加换行符
Log prints log information (for debugging traces) Formats output string and adds newline
参数 / Parameters:
- format: string - 格式化字符串(类似fmt.Printf) / Format string (similar to fmt.Printf)
- v: ...any - 格式化参数 / Format arguments
使用场景 / Use Cases:
- 调试HTTP请求过程 / Debugging HTTP request process
- 追踪网络连接状态 / Tracing network connection status
func LogS ¶
LogS 是默认的Stat统计信息处理函数,将统计信息打印到标准输出 该函数会格式化输出请求和响应的详细信息
LogS is the default Stat handler function that prints statistics to stdout This function formats and outputs detailed request and response information
参数 / Parameters:
- ctx: context.Context - 上下文对象(未使用,为了接口一致性) / Context object (unused, for interface consistency)
- stat: *Stat - 请求统计信息对象 / Request statistics object
输出格式 / Output Format:
- 如果没有响应URL,则输出完整的JSON格式的stat / If no response URL, outputs full JSON formatted stat
- 否则输出简化的日志格式,包含请求体和响应体 / Otherwise outputs simplified log format with request and response body
使用场景 / Use Cases:
- 作为Setup()的默认回调函数 / As the default callback function for Setup()
- 调试HTTP请求和响应 / Debugging HTTP requests and responses
- 监控请求性能和错误 / Monitoring request performance and errors
示例 / Example:
// 使用默认日志输出
// Use default logging output
session := requests.New(
requests.Setup(requests.LogS),
)
// 或者作为服务器中间件
// Or as server middleware
mux := requests.NewServeMux()
mux.Use(requests.Setup(requests.LogS))
func NewRequestWithContext ¶
NewRequestWithContext 使用给定的上下文和选项创建一个新的HTTP请求 NewRequestWithContext creates a new HTTP request with the given context and options
功能 / Features:
- 将请求体转换为适当的 io.Reader / Converting the request body to an appropriate io.Reader
- 设置请求方法和URL / Setting the request method and URL
- 追加路径段 / Appending path segments
- 设置查询参数 / Setting query parameters
- 设置请求头和Cookie / Setting headers and cookies
参数 / Parameters:
- ctx: 请求上下文,用于控制超时和取消 / Request context for controlling timeout and cancellation
- options: 请求选项配置 / Request options configuration
返回值 / Returns:
- *http.Request: 构造好的HTTP请求对象 / The constructed http.Request object
- error: 创建过程中的错误 / Error encountered during creation
示例 / Example:
options := Options{
Method: "POST",
URL: "https://api.example.com",
Path: []string{"/users", "/123"},
body: map[string]string{"name": "John"},
}
req, err := NewRequestWithContext(context.Background(), options)
func ParseBody ¶
func ParseBody(r io.ReadCloser) (*bytes.Buffer, error)
ParseBody 从 Request.Body 中解析并读取所有内容到内存缓冲区 该函数会自动处理空body和http.NoBody的情况
ParseBody parses and reads all content from Request.Body into a memory buffer This function automatically handles empty body and http.NoBody cases
参数 / Parameters:
- r: io.ReadCloser - 需要解析的请求体 / The request body to parse
返回值 / Returns:
- *bytes.Buffer: 包含请求体内容的缓冲区 / Buffer containing the request body content
- error: 读取过程中的错误 / Error during reading
使用场景 / Use Cases:
- 需要多次读取请求体内容时 / When you need to read request body multiple times
- 需要缓存请求体以便后续处理 / When you need to cache request body for later processing
- 中间件需要检查请求体内容 / When middleware needs to inspect request body
示例 / Example:
// 读取并缓存请求体
// Read and cache request body
buf, err := requests.ParseBody(req.Body)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Body content: %s\n", buf.String())
func Post ¶
Post 发送 POST 请求 Post sends a POST request
参数 / Parameters:
- url: 请求的URL地址 / The URL to request
- contentType: 内容类型,例如 "application/json" / Content type, e.g., "application/json"
- body: 请求体数据 / Request body data
返回值 / Returns:
- *http.Response: HTTP响应对象 / HTTP response object
- error: 请求过程中的错误 / Error during the request
示例 / Example:
body := strings.NewReader(`{"name": "John"}`)
resp, err := requests.Post("https://api.example.com/users", "application/json", body)
func PostForm ¶
PostForm 发送表单 POST 请求 自动设置 Content-Type 为 application/x-www-form-urlencoded PostForm sends a form POST request Automatically sets Content-Type to application/x-www-form-urlencoded
参数 / Parameters:
- url: 请求的URL地址 / The URL to request
- data: 表单数据 / Form data
返回值 / Returns:
- *http.Response: HTTP响应对象 / HTTP response object
- error: 请求过程中的错误 / Error during the request
示例 / Example:
data := url.Values{}
data.Set("username", "john")
data.Set("password", "secret")
resp, err := requests.PostForm("https://api.example.com/login", data)
func Put ¶
Put 发送 PUT 请求 Put sends a PUT request
参数 / Parameters:
- url: 请求的URL地址 / The URL to request
- contentType: 内容类型 / Content type
- body: 请求体数据 / Request body data
返回值 / Returns:
- *http.Response: HTTP响应对象 / HTTP response object
- error: 请求过程中的错误 / Error during the request
func SSE ¶
SSE 返回一个启用Server-Sent Events支持的中间件函数 该中间件会自动设置SSE所需的响应头并处理流的生命周期
SSE returns a middleware function that enables Server-Sent Events support The middleware automatically sets required SSE response headers and manages stream lifecycle
中间件功能 / Middleware Features:
- 设置适当的SSE响应头(Content-Type, Cache-Control等) / Sets appropriate SSE headers (Content-Type, Cache-Control, etc.)
- 创建ServerSentEvents包装器 / Creates ServerSentEvents wrapper for the response writer
- 通过defer确保流正确终止 / Ensures proper stream termination via deferred End() call
- 启用CORS跨域支持 / Enables CORS support for cross-origin requests
返回值 / Returns:
- func(next http.Handler) http.Handler: HTTP中间件函数 / HTTP middleware function
使用场景 / Use Cases:
- 实时数据推送 / Real-time data push
- 服务器主动通知客户端 / Server-initiated notifications to clients
- 长连接事件流 / Long-lived event streams
示例 / Example:
mux := requests.NewServeMux()
mux.GET("/events", requests.SSE()(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sse := w.(*requests.ServerSentEvents)
for i := 0; i < 10; i++ {
sse.Send("data", []byte(fmt.Sprintf(`{"count": %d}`, i)))
time.Sleep(time.Second)
}
})))
func Socket ¶
Socket 创建一个网络连接(公开函数) Socket creates a network connection (public function)
参数 / Parameters:
- ctx: 上下文 / Context
- opts: 配置选项 / Configuration options
返回值 / Returns:
- net.Conn: 网络连接 / Network connection
- error: 连接错误 / Connection error
使用说明 / Usage:
- 通过 requests.URL() 指定连接地址 / Specify connection address via requests.URL()
- 支持 TCP 和 Unix Socket / Supports TCP and Unix Socket
- 可以通过 requests.LocalAddr() 绑定本地地址 / Can bind local address via requests.LocalAddr()
- 可以通过 requests.Timeout() 设置超时 / Can set timeout via requests.Timeout()
示例 / Example:
// TCP 连接 / TCP connection
conn, err := requests.Socket(context.Background(),
requests.URL("tcp://example.com:80"),
requests.Timeout(10*time.Second),
)
// Unix Socket 连接 / Unix Socket connection
conn, err := requests.Socket(context.Background(),
requests.URL("unix:///tmp/app.sock"),
)
// 绑定本地地址 / Bind local address
localAddr := &net.TCPAddr{IP: net.ParseIP("192.168.1.100")}
conn, err := requests.Socket(context.Background(),
requests.URL("tcp://example.com:80"),
requests.LocalAddr(localAddr),
)
func WarpHandler ¶
WarpHandler 包装一个 http.Handler WarpHandler wraps an http.Handler
参数 / Parameters:
- next: 下一个处理器 / Next handler
返回值 / Returns:
- func(http.Handler) http.Handler: 中间件函数 / Middleware function
说明 / Notes:
- 这是一个装饰器模式的实现
- This is an implementation of the decorator pattern
func WarpRoundTripper ¶
func WarpRoundTripper(next http.RoundTripper) func(http.RoundTripper) http.RoundTripper
WarpRoundTripper 包装一个 http.RoundTripper 实例 WarpRoundTripper wraps an http.RoundTripper instance
参数 / Parameters:
- next: 下一个 RoundTripper / Next RoundTripper
返回值 / Returns:
- func(http.RoundTripper) http.RoundTripper: 装饰器函数 / Decorator function
说明 / Notes:
- 这是一个装饰器工厂函数 / This is a decorator factory function
- 用于为现有 RoundTripper 添加额外功能 / Used to add additional functionality to existing RoundTripper
示例 / Example:
middleware := requests.WarpRoundTripper(customRoundTripper) sess := requests.New(requests.Setup(middleware))
Types ¶
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node 是路由树(Trie树)的节点 Node is a node in the routing tree (Trie tree)
结构说明 / Structure:
- 使用前缀树(Trie)实现高效的路由匹配
- Uses a Trie tree for efficient route matching
- 支持最长前缀匹配原则
- Supports longest prefix matching
- 每个节点可以有多个 HTTP 方法的处理器
- Each node can have handlers for multiple HTTP methods
- 支持路径参数(通过 param 字段)
- Supports path parameters (via param field)
示例 / Example:
路由: /api/users/123/profile 树结构: / -> api -> users -> 123 -> profile Route: /api/users/123/profile Tree: / -> api -> users -> 123 -> profile 路由: /api/users/:id 树结构: / -> api -> users -> param(name="id") -> ... Route: /api/users/:id Tree: / -> api -> users -> param(name="id") -> ...
func NewNode ¶
NewNode 创建一个新的路由树节点 NewNode creates a new routing tree node
参数 / Parameters:
- path: 路径片段 / Path segment
- h: 默认处理器 / Default handler
- opts: 配置选项 / Configuration options
返回值 / Returns:
- *Node: 新创建的节点 / Newly created node
func (*Node) Add ¶
func (node *Node) Add(path string, h http.HandlerFunc, opts ...Option)
Add 向路由树中添加一个路由 Add adds a route to the routing tree
参数 / Parameters:
- path: 路由路径(如 "/api/users" 或 "/api/users/:id")/ Route path (e.g., "/api/users" or "/api/users/:id")
- h: 处理函数 / Handler function
- opts: 配置选项(可以指定 HTTP 方法)/ Configuration options (can specify HTTP method)
实现原理 / Implementation:
- 按照 "/" 分割路径 / Split path by "/"
- 逐级创建树节点 / Create tree nodes level by level
- 支持路径参数(:id 或 {id} 语法)/ Supports path parameters (:id or {id} syntax)
- 支持路径覆盖(后注册的会覆盖先注册的)/ Supports path override (later registration overrides earlier)
路径参数语法 / Path parameter syntax:
- :id 风格(兼容 Gin、Echo 等框架)/ :id style (compatible with Gin, Echo, etc.)
- {id} 风格(兼容 Go 1.22+ 标准库)/ {id} style (compatible with Go 1.22+ standard library)
示例 / Example:
node.Add("/api/users", handler, requests.Method("GET"))
node.Add("/api/users/:id", handler, requests.Method("POST"))
node.Add("/api/users/{id}", handler, requests.Method("PUT"))
func (*Node) Find ¶
Find 在路由树中查找匹配的节点(按照最长匹配原则) Find finds a matching node in the routing tree (using longest prefix matching)
参数 / Parameters:
- path: 要查找的路径 / Path to find
- r: HTTP 请求(用于设置路径参数值)/ HTTP request (for setting path parameter values)
返回值 / Returns:
- *Node: 匹配的节点 / Matched node
- bool: 是否完全匹配(所有路径段都匹配)/ Whether it's a complete match (all path segments matched)
匹配原则 / Matching Rules:
- 精确匹配优先于参数匹配 / Exact match takes priority over parameter match
- 静态路径优先于参数路径 / Static paths take priority over parameter paths
- 如果匹配到参数,会自动调用 r.SetPathValue() 设置参数值
- If a parameter is matched, r.SetPathValue() is automatically called to set the parameter value
示例 / Example:
node, matched := node.Find("/api/users/123", r)
if matched {
// 完全匹配,可以使用 r.PathValue("id") 获取参数值
// Complete match, can use r.PathValue("id") to get parameter value
}
type Option ¶
type Option func(*Options)
Option 是用于配置 Options 的函数类型 Option is a function type for configuring Options
这是一种常见的函数式选项模式(Functional Options Pattern) This is a common Functional Options Pattern
优点 / Advantages:
- 可选参数:不需要的参数可以不传 / Optional parameters: no need to pass unused parameters
- 可扩展性:添加新选项不影响现有代码 / Extensibility: adding new options doesn't affect existing code
- 可读性:每个选项的意义一目了然 / Readability: each option's meaning is clear
示例 / Example:
// 定义一个自定义选项
// Define a custom option
func MyCustomOption(value string) requests.Option {
return func(o *requests.Options) {
o.Header.Set("X-Custom", value)
}
}
// 使用自定义选项
// Use custom option
sess := requests.New(MyCustomOption("my-value"))
func BasicAuth ¶
BasicAuth 设置 HTTP 基本认证 BasicAuth sets HTTP Basic Authentication
自动设置的头部 / Automatically set headers:
- Authorization: Basic <base64(username:password)>
参数 / Parameters:
- username: 用户名 / Username
- password: 密码 / Password
示例 / Example:
sess := requests.New(
requests.URL("https://api.example.com"),
requests.BasicAuth("admin", "secret123"),
)
func Body ¶
Body 设置请求体内容 Body sets the request body content
支持的类型 / Supported Types:
- string: 字符串内容 / String content
- []byte: 字节数组 / Byte array
- io.Reader: 任何读取器 / Any reader
- url.Values: 表单数据 / Form data
- struct/map: 自动序列化为JSON / Auto-serialized to JSON
参数 / Parameters:
- body: 请求体数据 / Request body data
示例 / Example:
// 字符串
// String
requests.Body("plain text")
// JSON(自动序列化)
// JSON (auto-serialized)
requests.Body(map[string]string{"name": "John"})
// 表单
// Form
form := url.Values{}
form.Set("username", "john")
requests.Body(form)
func CertKey ¶
CertKey 设置 TLS/SSL 证书和密钥文件路径(用于HTTPS服务器) CertKey sets TLS/SSL certificate and key file paths (for HTTPS server)
参数 / Parameters:
- cert: 证书文件路径 / Certificate file path
- key: 密钥文件路径 / Key file path
示例 / Example:
// 创建 HTTPS 服务器
// Create HTTPS server
mux := requests.NewServeMux(
requests.URL("0.0.0.0:443"),
requests.CertKey("/path/to/cert.pem", "/path/to/key.pem"),
)
requests.ListenAndServe(context.Background(), mux)
func Cookie ¶
Cookie 添加单个 Cookie Cookie adds a single cookie
参数 / Parameters:
- cookie: Cookie 对象 / Cookie object
示例 / Example:
cookie := http.Cookie{
Name: "session_id",
Value: "abc123",
}
resp, _ := sess.DoRequest(context.Background(),
requests.Cookie(cookie),
)
func Cookies ¶
Cookies 批量添加 Cookies Cookies adds multiple cookies at once
参数 / Parameters:
- cookies: Cookie 对象列表 / Cookie objects list
示例 / Example:
cookies := []http.Cookie{
{Name: "session_id", Value: "abc123"},
{Name: "user_id", Value: "user456"},
}
resp, _ := sess.DoRequest(context.Background(),
requests.Cookies(cookies...),
)
func Form ¶
Form 设置表单数据(自动设置 Content-Type) Form sets form data (automatically sets Content-Type)
自动设置的头部 / Automatically set headers:
- Content-Type: application/x-www-form-urlencoded
参数 / Parameters:
- form: 表单数据 / Form data
示例 / Example:
form := url.Values{}
form.Set("username", "john")
form.Set("password", "secret123")
resp, _ := sess.DoRequest(context.Background(),
requests.MethodPost,
requests.Path("/login"),
requests.Form(form),
)
func Gzip ¶
Gzip 对请求体进行 gzip 压缩 Gzip compresses the request body using gzip
自动设置的头部 / Automatically set headers:
- Accept-Encoding: gzip
- Content-Encoding: gzip
参数 / Parameters:
- body: 要压缩的内容 / Content to compress
使用场景 / Use Cases:
- 发送大量数据时,减少网络传输量 / Reduce network transmission when sending large data
- 服务器支持 gzip 解压时 / When server supports gzip decompression
示例 / Example:
largeData := strings.Repeat("data", 10000)
resp, _ := sess.DoRequest(context.Background(),
requests.MethodPost,
requests.Gzip(largeData), // 自动压缩 / Auto-compressed
)
func Header ¶
Header 添加单个 HTTP 请求头 Header adds a single HTTP header
参数 / Parameters:
- k: 请求头名称 / Header name
- v: 请求头值 / Header value
示例 / Example:
sess := requests.New(
requests.Header("Authorization", "Bearer token123"),
requests.Header("Accept", "application/json"),
)
func Headers ¶
Headers 批量添加 HTTP 请求头 Headers adds multiple HTTP headers at once
参数 / Parameters:
- kv: 请求头映射表 / Headers map
示例 / Example:
headers := map[string]string{
"Authorization": "Bearer token123",
"Accept": "application/json",
"X-Request-ID": "abc-123",
}
resp, _ := sess.DoRequest(context.Background(),
requests.Headers(headers),
)
func Host ¶
Host 设置请求的 Host 头(用于虚拟主机或代理场景) Host sets the request Host header (for virtual host or proxy scenarios)
参数 / Parameters:
- host: 主机名 / Host name
说明 / Notes:
- 在客户端,Host字段(可选地)用来重写请求的Host头
- On client side, Host field (optionally) overrides the request Host header
- 如果为空,Request.Write 方法会使用 URL 字段的 Host
- If empty, Request.Write method uses Host from URL field
使用场景 / Use Cases:
- 通过IP访问,但需要指定域名(绕过DNS)
- Access by IP but need to specify domain name (bypass DNS)
- 虚拟主机环境 / Virtual host environment
示例 / Example:
// 直接访问IP,但设置Host头
// Access by IP directly but set Host header
resp, _ := sess.DoRequest(context.Background(),
requests.URL("http://192.168.1.100"),
requests.Host("api.example.com"),
)
func LocalAddr ¶
LocalAddr 绑定本地网络地址 LocalAddr binds local network address
参数 / Parameters:
- addr: 本地地址 / Local address
- TCP: &net.TCPAddr{IP: net.ParseIP("192.168.1.100")}
- Unix: &net.UnixAddr{Net: "unix", Name: "/tmp/socket"}
使用场景 / Use Cases:
- 服务器有多个网卡时,指定出口IP / Specify outbound IP when server has multiple NICs
- 需要使用Unix Domain Socket / Need to use Unix Domain Socket
示例 / Example:
// 绑定特定IP
// Bind to specific IP
localAddr := &net.TCPAddr{IP: net.ParseIP("192.168.1.100")}
sess := requests.New(
requests.URL("https://api.example.com"),
requests.LocalAddr(localAddr),
)
func Logf ¶
Logf 启用请求/响应日志记录 Logf enables request/response logging
参数 / Parameters:
- f: 日志处理函数 / Log handler function
功能 / Features:
- 同时记录客户端和服务器端的请求 / Logs both client and server requests
- 记录详细的统计信息 / Records detailed statistics
示例 / Example:
// 使用默认日志函数
// Use default log function
sess := requests.New(
requests.URL("https://api.example.com"),
requests.Logf(requests.LogS),
)
// 自定义日志函数
// Custom log function
customLog := func(ctx context.Context, stat *requests.Stat) {
log.Printf("Request to %s took %dms", stat.Request.URL, stat.Cost)
}
sess := requests.New(requests.Logf(customLog))
func MaxConns ¶
MaxConns 设置最大连接数(连接池大小) MaxConns sets the maximum number of connections (connection pool size)
参数 / Parameters:
- conn: 最大连接数 / Maximum number of connections
说明 / Notes:
- 该值同时设置 MaxIdleConns 和 MaxIdleConnsPerHost
- This value sets both MaxIdleConns and MaxIdleConnsPerHost
- 默认值为 100 / Default is 100
- 适当增大可以提高并发性能 / Increasing properly can improve concurrent performance
示例 / Example:
sess := requests.New(
requests.URL("https://api.example.com"),
requests.MaxConns(200), // 支持200个并发连接 / Support 200 concurrent connections
)
func Method ¶
Method 设置 HTTP 请求方法 Method sets the HTTP request method
参数 / Parameters:
- method: HTTP 方法(GET、POST、PUT、DELETE等)/ HTTP method (GET, POST, PUT, DELETE, etc.)
示例 / Example:
// 使用预定义常量
// Use pre-defined constants
resp, _ := sess.Do(context.Background(), requests.MethodGet)
// 使用自定义方法
// Use custom method
resp, _ := sess.Do(context.Background(), requests.Method("PATCH"))
func OnShutdown ¶
OnShutdown 设置服务器关闭时的回调函数 OnShutdown sets the callback function when server shuts down
参数 / Parameters:
- f: 关闭回调函数 / Shutdown callback function
示例 / Example:
mux := requests.NewServeMux(
requests.URL("0.0.0.0:8080"),
requests.OnShutdown(func(s *http.Server) {
log.Printf("Server %s shutting down", s.Addr)
// 清理资源 / Clean up resources
}),
)
func OnStart ¶
OnStart 设置服务器启动时的回调函数 OnStart sets the callback function when server starts
参数 / Parameters:
- f: 启动回调函数 / Start callback function
示例 / Example:
mux := requests.NewServeMux(
requests.URL("0.0.0.0:8080"),
requests.OnStart(func(s *http.Server) {
log.Printf("Server started on %s", s.Addr)
}),
)
func Param ¶
Param 添加单个 URL 查询参数(支持同名参数多值) Param adds a single URL query parameter (supports multiple values for same key)
参数 / Parameters:
- k: 参数名 / Parameter name
- v: 参数值(可以有多个)/ Parameter values (can be multiple)
示例 / Example:
// 添加单个值
// Add single value
requests.Param("page", "1")
// 添加多个值(同名参数)
// Add multiple values (same parameter name)
requests.Param("tags", "go", "http", "client") // tags=go&tags=http&tags=client
func Params ¶
Params 批量添加 URL 查询参数 Params adds multiple URL query parameters at once
参数 / Parameters:
- query: 查询参数映射表 / Query parameters map
示例 / Example:
params := map[string]string{
"page": "1",
"size": "20",
"sort": "created_at",
}
resp, _ := sess.DoRequest(context.Background(),
requests.Path("/users"),
requests.Params(params), // /users?page=1&size=20&sort=created_at
)
func Path ¶
Path 追加 URL 路径片段 Path appends URL path segment
特点 / Features:
- 可以多次调用,路径会依次追加 / Can be called multiple times, paths are appended sequentially
- 自动处理路径拼接 / Automatically handles path concatenation
参数 / Parameters:
- path: 路径片段 / Path segment
示例 / Example:
sess := requests.New(requests.URL("https://api.example.com"))
resp, _ := sess.DoRequest(context.Background(),
requests.Path("/users"), // https://api.example.com/users
requests.Path("/123"), // https://api.example.com/users/123
requests.Path("/profile"), // https://api.example.com/users/123/profile
)
func Proxy ¶
Proxy 设置代理服务器地址 Proxy sets the proxy server address
参数 / Parameters:
- addr: 代理地址 / Proxy address
- HTTP代理: "http://proxy.example.com:8080"
- HTTPS代理: "https://proxy.example.com:8080"
- SOCKS5代理: "socks5://proxy.example.com:1080"
环境变量方式 / Environment Variable Alternative:
- os.Setenv("HTTP_PROXY", "http://127.0.0.1:8080")
- os.Setenv("HTTPS_PROXY", "https://127.0.0.1:8080")
示例 / Example:
// 使用HTTP代理
// Use HTTP proxy
sess := requests.New(
requests.URL("https://api.example.com"),
requests.Proxy("http://proxy.company.com:8080"),
)
// 使用SOCKS5代理
// Use SOCKS5 proxy
sess := requests.New(
requests.Proxy("socks5://127.0.0.1:1080"),
)
func RoundTripper ¶
func RoundTripper(tr http.RoundTripper) Option
RoundTripper 设置自定义的 HTTP 传输层 RoundTripper sets custom HTTP transport layer
参数 / Parameters:
- tr: 自定义的 RoundTripper 实现 / Custom RoundTripper implementation
使用场景 / Use Cases:
- 完全自定义传输行为 / Fully customize transport behavior
- 使用第三方传输实现 / Use third-party transport implementation
- 高级连接池管理 / Advanced connection pool management
示例 / Example:
// 使用自定义传输层
// Use custom transport
customTransport := &http.Transport{
MaxIdleConns: 200,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
}
sess := requests.New(
requests.RoundTripper(customTransport),
)
func Setup ¶
func Setup(fn ...func(tripper http.RoundTripper) http.RoundTripper) Option
Setup 注册客户端中间件(用于请求/响应处理) Setup registers client middleware (for request/response processing)
参数 / Parameters:
- fn: 中间件函数列表 / Middleware function list
中间件执行顺序 / Middleware Execution Order:
- 按照注册的反序执行 / Executed in reverse order of registration
- 最先注册的最外层,最后注册的最内层 / First registered is outermost, last is innermost
示例 / Example:
// 自定义中间件:添加请求ID
// Custom middleware: add request ID
requestIDMiddleware := func(next http.RoundTripper) http.RoundTripper {
return requests.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
req.Header.Set("X-Request-ID", uuid.New().String())
return next.RoundTrip(req)
})
}
sess := requests.New(
requests.URL("https://api.example.com"),
requests.Setup(requestIDMiddleware),
)
func Stream ¶
Stream 启用流式处理模式(用于大文件下载或实时数据流) Stream enables streaming mode (for large file downloads or real-time data streams)
参数 / Parameters:
- stream: 流处理回调函数 func(lineNumber int64, lineContent []byte) error
特点 / Features:
- 边接收边处理,不缓存全部内容 / Process while receiving, no full content caching
- 按行分割数据 / Split data by lines
- 适合大文件和实时流 / Suitable for large files and real-time streams
示例 / Example:
// 下载大文件并实时处理
// Download large file and process in real-time
resp, _ := sess.DoRequest(context.Background(),
requests.Stream(func(lineNum int64, line []byte) error {
fmt.Printf("Line %d: %s", lineNum, line)
return nil
}),
)
func Timeout ¶
Timeout 设置请求超时时间 Timeout sets the request timeout duration
参数 / Parameters:
- timeout: 超时时间 / Timeout duration
说明 / Notes:
- 默认值为 30 秒 / Default is 30 seconds
- 超时会返回 context deadline exceeded 错误
- Timeout returns context deadline exceeded error
示例 / Example:
// 会话级超时
// Session-level timeout
sess := requests.New(requests.Timeout(10*time.Second))
// 请求级超时(覆盖会话配置)
// Request-level timeout (overrides session config)
resp, _ := sess.DoRequest(context.Background(),
requests.Timeout(5*time.Second),
)
func Trace ¶
Trace 启用HTTP请求追踪,打印请求和响应的详细信息 包括HTTP头、请求体、响应体等,适用于调试和开发环境
Trace enables HTTP request tracing, prints detailed request and response information Includes HTTP headers, request body, response body, etc., suitable for debugging and development
参数 / Parameters:
- mLimit: ...int - 可选的最大显示长度(默认10240字节),超过则截断 / Optional maximum display length (default 10240 bytes), truncate if exceeded
返回值 / Returns:
- Option: 配置选项函数 / Configuration option function
追踪内容 / Traced Content:
- DNS解析过程 / DNS resolution process
- TCP连接建立 / TCP connection establishment
- TLS握手过程 / TLS handshake process
- HTTP请求完整内容 / Complete HTTP request content
- HTTP响应完整内容 / Complete HTTP response content
性能注意 / Performance Note:
- 会复制并缓存请求和响应体,增加内存开销 / Copies and caches request and response bodies, increasing memory overhead
- 仅建议在开发和调试环境使用 / Recommended only for development and debugging environments
- 生产环境建议使用Setup()进行轻量级日志 / Use Setup() for lightweight logging in production
使用场景 / Use Cases:
- 调试API调用问题 / Debugging API call issues
- 分析HTTP通信细节 / Analyzing HTTP communication details
- 开发环境请求监控 / Request monitoring in development
- 学习HTTP协议 / Learning HTTP protocol
示例 / Example:
// 启用请求追踪
// Enable request tracing
session := requests.New(requests.Trace())
resp, _ := session.DoRequest(ctx, requests.URL("https://api.example.com/users"))
// 自定义截断长度为5000字节
// Custom truncate length to 5000 bytes
session := requests.New(requests.Trace(5000))
func URL ¶
URL 设置请求的目标 URL URL sets the target URL for the request
支持的协议 / Supported Protocols:
- http:// - 标准 HTTP 协议 / Standard HTTP protocol
- https:// - 安全 HTTPS 协议 / Secure HTTPS protocol
- unix:// - Unix Domain Socket / Unix Domain Socket
Unix Socket 使用说明 / Unix Socket Usage:
// 会话级别设置 socket 路径
// Set socket path at session level
sess := requests.New(requests.URL("unix:///tmp/requests.sock"))
// 请求级别设置 HTTP URL
// Set HTTP URL at request level
resp, _ := sess.DoRequest(context.Background(),
requests.URL("http://localhost/api/users"),
requests.Body("data"),
)
参数 / Parameters:
- url: 目标 URL 地址 / Target URL address
示例 / Example:
sess := requests.New(requests.URL("https://api.example.com"))
func Use ¶
Use 注册服务器中间件(用于HTTP服务器请求处理) Use registers server middleware (for HTTP server request processing)
参数 / Parameters:
- fn: 中间件函数列表 / Middleware function list
常见用途 / Common Uses:
- 日志记录 / Logging
- 认证授权 / Authentication/Authorization
- CORS处理 / CORS handling
- 请求限流 / Rate limiting
示例 / Example:
// 自定义日志中间件
// Custom logging middleware
loggingMiddleware := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Request: %s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
mux := requests.NewServeMux(
requests.URL("0.0.0.0:8080"),
requests.Use(loggingMiddleware),
)
func Verify ¶
Verify 设置是否验证 TLS/SSL 证书 Verify sets whether to verify TLS/SSL certificates
参数 / Parameters:
- verify: true-验证证书,false-跳过验证 / true-verify certificates, false-skip verification
警告 / Warning:
- 生产环境应始终验证证书(verify=true)
- Production should always verify certificates (verify=true)
- 仅在测试或开发环境中跳过验证
- Skip verification only in testing or development environments
示例 / Example:
// 开发环境,跳过证书验证
// Development environment, skip certificate verification
sess := requests.New(
requests.URL("https://localhost:8443"),
requests.Verify(false),
)
type Options ¶
type Options struct {
// ===== HTTP 请求基础配置 / HTTP Request Basic Configuration =====
Method string // HTTP方法(GET、POST等)/ HTTP method (GET, POST, etc.)
URL string // 目标URL / Target URL
Path []string // URL路径片段(会追加到URL后)/ URL path segments (appended to URL)
RawQuery url.Values // URL查询参数 / URL query parameters
Header http.Header // HTTP请求头 / HTTP headers
Cookies []http.Cookie // HTTP Cookies
// ===== 客户端配置 / Client Configuration =====
Timeout time.Duration // 请求超时时间 / Request timeout
MaxConns int // 最大连接数(连接池大小)/ Maximum connections (connection pool size)
Verify bool // 是否验证TLS证书 / Whether to verify TLS certificates
// ===== 传输层配置 / Transport Layer Configuration =====
Transport http.RoundTripper // 自定义传输层 / Custom transport
HttpRoundTripper []func(http.RoundTripper) http.RoundTripper // 客户端中间件链 / Client middleware chain
// ===== 服务器配置 / Server Configuration =====
Handler http.Handler // HTTP处理器 / HTTP handler
HttpHandler []func(http.Handler) http.Handler // 服务器中间件链 / Server middleware chain
OnStart func(*http.Server) // 服务器启动回调 / Server start callback
OnShutdown func(*http.Server) // 服务器关闭回调 / Server shutdown callback
// ===== 网络配置 / Network Configuration =====
LocalAddr net.Addr // 本地地址绑定 / Local address binding
Proxy func(*http.Request) (*url.URL, error) // 代理配置函数 / Proxy configuration function
// contains filtered or unexported fields
}
Options 是请求和会话的配置选项集合 Options is the collection of configuration options for requests and sessions
设计理念 / Design Philosophy:
- 客户端配置(Client):URL、Header、Timeout、Proxy 等
- 服务器配置(Server):Handler、OnStart、OnShutdown 等
- 传输层配置(Transport):MaxConns、Verify、LocalAddr 等
- 中间件配置(Middleware):HttpRoundTripper、HttpHandler 等
两级配置系统 / Two-Level Configuration System:
- 会话级别(Session-level):创建Session时设置,对所有请求生效
- 请求级别(Request-level):单次请求时设置,可覆盖会话配置
示例 / Example:
// 会话级配置
// Session-level configuration
opts := []requests.Option{
requests.URL("https://api.example.com"),
requests.Timeout(30*time.Second),
requests.Header("Authorization", "Bearer token"),
}
sess := requests.New(opts...)
// 请求级配置(覆盖会话配置)
// Request-level configuration (overrides session config)
resp, _ := sess.DoRequest(context.Background(),
requests.Path("/users"),
requests.Timeout(10*time.Second), // 覆盖会话的30秒超时 / Override session's 30s timeout
)
type ParamNode ¶
type ParamNode struct {
// contains filtered or unexported fields
}
ParamNode 表示一个路径参数节点 ParamNode represents a path parameter node
用于存储路径参数信息,支持 :id 和 {id} 两种语法 Used to store path parameter information, supports both :id and {id} syntaxes
示例 / Example:
路由: /api/users/:id 参数节点: name="id", node=子节点树 Route: /api/users/:id ParamNode: name="id", node=child node tree
type Response ¶
type Response struct {
*http.Request // 原始 HTTP 请求 / Original HTTP request
*http.Response // 原始 HTTP 响应 / Original HTTP response
StartAt time.Time // 请求开始时间 / Request start time
Cost time.Duration // 请求耗时 / Request duration
Content *bytes.Buffer // 响应内容缓存(已自动读取)/ Response content cache (auto-read)
Err error // 请求过程中的错误 / Error during request
}
Response 包装了 http.Response 结构体,提供了额外的功能 Response wraps http.Response struct with additional features
主要功能 / Main Features:
- 记录请求开始时间和耗时 / Record request start time and duration
- 自动缓存响应内容 / Automatically cache response content
- 统一的错误处理 / Unified error handling
- 统计信息收集 / Statistics collection
- 自动安全关闭响应体 / Auto-safe close response body
使用场景 / Use Cases:
- 需要记录请求耗时 / Need to track request duration
- 需要多次读取响应内容 / Need to read response content multiple times
- 需要收集请求统计信息 / Need to collect request statistics
- 希望自动处理响应体关闭 / Want automatic response body closing
示例 / Example:
sess := requests.New(requests.URL("https://api.example.com"))
resp, err := sess.DoRequest(context.Background())
if err != nil {
log.Fatal(err)
}
// Content已经自动缓存,无需担心Body关闭问题
// Content is auto-cached, no need to worry about Body closing
fmt.Println(resp.Content.String())
fmt.Printf("Request took %v\n", resp.Cost)
func (*Response) Error ¶
Error 实现 error 接口 Error implements the error interface
允许 Response 对象作为 error 类型使用 Allows Response object to be used as an error type
返回值 / Returns:
- string: 错误信息,如果没有错误则返回空字符串 / Error message, or empty string if no error
func (*Response) JSON ¶
JSON 将响应内容反序列化为指定的类型 JSON deserializes the response content into the specified type
参数 / Parameters:
- v: 接收反序列化结果的指针 / Pointer to receive deserialized result
返回值 / Returns:
- error: 反序列化错误 / Deserialization error
示例 / Example:
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
var user User
if err := resp.JSON(&user); err != nil {
log.Fatal(err)
}
fmt.Printf("User: %s, Age: %d\n", user.Name, user.Age)
func (*Response) Stat ¶
Stat 返回请求的统计信息 Stat returns the request statistics
包括 / Includes:
- 请求和响应的详细信息 / Detailed request and response information
- 请求耗时 / Request duration
- 请求和响应的头部信息 / Request and response headers
- 请求和响应的内容 / Request and response content
返回值 / Returns:
- *Stat: 统计信息对象 / Statistics object
示例 / Example:
resp, _ := sess.DoRequest(context.Background())
stat := resp.Stat()
fmt.Printf("Request took %dms\n", stat.Cost)
fmt.Printf("Status code: %d\n", stat.Response.StatusCode)
func (*Response) String ¶
String 实现 fmt.Stringer 接口 String implements the fmt.Stringer interface
返回响应内容的字符串形式,便于打印和调试 Returns the string representation of response content for easy printing and debugging
返回值 / Returns:
- string: 响应内容的字符串 / String representation of response content
示例 / Example:
resp, _ := sess.DoRequest(context.Background()) fmt.Println(resp.String()) // 打印完整响应内容 / Print full response content
type ResponseWriter ¶
type ResponseWriter struct {
http.ResponseWriter
StatusCode int // HTTP响应状态码 / HTTP response status code
Content *bytes.Buffer // 响应内容的缓存 / Response content cache
// contains filtered or unexported fields
}
ResponseWriter 包装了http.ResponseWriter接口,提供了额外的功能 主要用于服务器端中间件,支持响应内容捕获和并发安全访问
ResponseWriter wraps http.ResponseWriter interface with additional features Mainly used for server-side middleware, supporting response content capture and concurrent-safe access
核心功能 / Core Features:
- 记录响应状态码 / Records response status code
- 缓存响应内容 / Caches response content
- 支持并发安全的读写操作 / Supports concurrent-safe read/write operations
- 实现多个标准接口 / Implements multiple standard interfaces: - http.ResponseWriter - http.Flusher - http.Pusher - http.Hijacker - io.Reader - io.Writer
使用场景 / Use Cases:
- 中间件需要记录响应内容 / Middleware needs to record response content
- 日志记录完整响应 / Logging complete responses
- 响应内容分析和监控 / Response content analysis and monitoring
- 实现自定义响应处理逻辑 / Implementing custom response handling logic
并发安全 / Concurrency Safety:
- 所有方法都使用互斥锁保护 / All methods are protected by mutex
- 可以从多个goroutine安全访问 / Can be safely accessed from multiple goroutines
示例 / Example:
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ww := requests.NewResponseWriter(w)
next.ServeHTTP(ww, r)
// 可以访问响应状态码和内容
// Can access response status code and content
log.Printf("Status: %d, Body: %s", ww.StatusCode, ww.Content.String())
})
}
func NewResponseWriter ¶
func NewResponseWriter(w http.ResponseWriter) *ResponseWriter
NewResponseWriter 创建一个新的ResponseWriter实例 默认状态码为200 OK
NewResponseWriter creates a new ResponseWriter instance Default status code is 200 OK
参数 / Parameters:
- w: http.ResponseWriter - 原始的ResponseWriter / Original ResponseWriter
返回值 / Returns:
- *ResponseWriter: 包装后的ResponseWriter / Wrapped ResponseWriter
示例 / Example:
func handler(w http.ResponseWriter, r *http.Request) {
ww := requests.NewResponseWriter(w)
ww.Write([]byte("Hello, World!"))
fmt.Printf("Response: %s\n", ww.Content.String())
}
func (*ResponseWriter) Flush ¶
func (w *ResponseWriter) Flush()
Flush 实现http.Flusher接口,立即将缓冲的数据发送到客户端 用于实时流式响应(如Server-Sent Events)
Flush implements http.Flusher interface, immediately sends buffered data to client Used for real-time streaming responses (e.g., Server-Sent Events)
并发安全 / Concurrency Safety:
- 方法内部使用互斥锁保护 / Protected by mutex internally
使用场景 / Use Cases:
- Server-Sent Events (SSE)
- 流式响应 / Streaming responses
- 长轮询 / Long polling
- 实时数据推送 / Real-time data push
注意事项 / Notes:
- 调用Flush后响应头会被立即发送 / Response headers are sent immediately after calling Flush
- 如果底层ResponseWriter不支持Flush,会panic / Panics if underlying ResponseWriter doesn't support Flush
示例 / Example:
ww.Write([]byte("data: message 1\n\n"))
ww.Flush() // 立即发送给客户端 / Send to client immediately
func (*ResponseWriter) Hijack ¶
func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack 实现http.Hijacker接口,允许接管HTTP连接 用于WebSocket或其他需要直接操作底层连接的场景
Hijack implements http.Hijacker interface, allows taking over the HTTP connection Used for WebSocket or other scenarios requiring direct connection manipulation
返回值 / Returns:
- net.Conn: 底层网络连接 / Underlying network connection
- *bufio.ReadWriter: 带缓冲的读写器 / Buffered reader/writer
- error: 接管错误 / Hijack error
并发安全 / Concurrency Safety:
- 方法内部使用互斥锁保护 / Protected by mutex internally
使用场景 / Use Cases:
- WebSocket协议升级 / WebSocket protocol upgrade
- 自定义协议实现 / Custom protocol implementation
- 直接TCP连接操作 / Direct TCP connection operations
注意事项 / Notes:
- Hijack后ResponseWriter不再可用 / ResponseWriter is no longer usable after Hijack
- 调用者负责关闭连接 / Caller is responsible for closing the connection
- 如果底层不支持Hijack,会panic / Panics if underlying doesn't support Hijack
示例 / Example:
// WebSocket升级示例
// WebSocket upgrade example
conn, rw, err := ww.Hijack()
if err != nil {
log.Fatal(err)
}
defer conn.Close()
// 现在可以直接操作conn和rw
// Now can directly operate on conn and rw
func (*ResponseWriter) Push ¶
func (w *ResponseWriter) Push(target string, opts *http.PushOptions) error
Push 实现http.Pusher接口,支持HTTP/2服务器推送功能 允许服务器主动向客户端推送资源
Push implements http.Pusher interface, supports HTTP/2 server push Allows server to proactively push resources to client
参数 / Parameters:
- target: string - 要推送的资源路径 / Path of resource to push
- opts: *http.PushOptions - 推送选项(可为nil) / Push options (can be nil)
返回值 / Returns:
- error: 推送错误 / Push error
并发安全 / Concurrency Safety:
- 方法内部使用互斥锁保护 / Protected by mutex internally
使用场景 / Use Cases:
- 预加载关键资源(CSS, JS) / Preload critical resources (CSS, JS)
- 优化页面加载性能 / Optimize page load performance
- HTTP/2服务器推送 / HTTP/2 server push
注意事项 / Notes:
- 仅在HTTP/2连接上有效 / Only effective on HTTP/2 connections
- 如果底层不支持Push,会panic / Panics if underlying doesn't support Push
示例 / Example:
// 推送CSS文件
// Push CSS file
ww.Push("/static/style.css", &http.PushOptions{
Header: http.Header{"Content-Type": []string{"text/css"}},
})
func (*ResponseWriter) Read ¶
func (w *ResponseWriter) Read(b []byte) (int, error)
Read 实现io.Reader接口,从内容缓存中读取数据 通常用于中间件读取已写入的响应内容
Read implements io.Reader interface, reads data from content cache Typically used by middleware to read written response content
参数 / Parameters:
- b: []byte - 读取数据的目标缓冲区 / Target buffer for reading data
返回值 / Returns:
- int: 读取的字节数 / Number of bytes read
- error: 读取错误(io.EOF表示读取完毕) / Read error (io.EOF indicates end of data)
并发安全 / Concurrency Safety:
- 方法内部使用互斥锁保护 / Protected by mutex internally
注意事项 / Notes:
- 读取操作会消耗缓存内容 / Read operation consumes cache content
- 如需多次读取,应先保存Content / To read multiple times, save Content first
示例 / Example:
data := make([]byte, 1024)
n, err := ww.Read(data)
fmt.Printf("Read %d bytes: %s\n", n, string(data[:n]))
func (*ResponseWriter) Write ¶
func (w *ResponseWriter) Write(b []byte) (int, error)
Write 实现io.Writer接口,写入响应体数据 数据会同时写入原始ResponseWriter和内容缓存
Write implements io.Writer interface, writes response body data Data is written to both original ResponseWriter and content cache
参数 / Parameters:
- b: []byte - 要写入的数据 / Data to write
返回值 / Returns:
- int: 写入的字节数 / Number of bytes written
- error: 写入错误 / Write error
并发安全 / Concurrency Safety:
- 方法内部使用互斥锁保护 / Protected by mutex internally
行为特性 / Behavior:
- 首次调用会自动触发WriteHeader(200) / First call automatically triggers WriteHeader(200)
- 数据会被复制到内部缓存 / Data is copied to internal cache
- 如果写入原始ResponseWriter失败,不会写入缓存 / If writing to original ResponseWriter fails, cache is not updated
示例 / Example:
ww.Write([]byte("Hello, World!"))
fmt.Printf("Cached content: %s\n", ww.Content.String())
func (*ResponseWriter) WriteHeader ¶
func (w *ResponseWriter) WriteHeader(statusCode int)
WriteHeader 设置HTTP响应状态码 该方法确保状态码只被设置一次(幂等性)
WriteHeader sets the HTTP response status code This method ensures the status code is set only once (idempotent)
参数 / Parameters:
- statusCode: int - HTTP状态码(例如:200, 404, 500等) / HTTP status code (e.g., 200, 404, 500, etc.)
并发安全 / Concurrency Safety:
- 方法内部使用互斥锁保护 / Protected by mutex internally
注意事项 / Notes:
- 如果已经调用过WriteHeader,再次调用会被忽略 / Subsequent calls are ignored if WriteHeader was already called
- 调用Write()会自动触发WriteHeader(200) / Calling Write() automatically triggers WriteHeader(200)
示例 / Example:
ww.WriteHeader(http.StatusNotFound)
ww.Write([]byte("Not Found"))
type RoundTripperFunc ¶
RoundTripperFunc 是 http.RoundTripper 接口的函数式实现 RoundTripperFunc is a functional implementation of the http.RoundTripper interface
说明 / Notes:
- 允许将普通函数转换为 RoundTripper 接口 / Allows converting regular functions to RoundTripper interface
- 便于函数式扩展 / Facilitates functional extensions
- 是实现中间件的核心类型 / Core type for implementing middleware
示例 / Example:
rt := requests.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
// 添加自定义请求头 / Add custom header
req.Header.Set("X-Custom", "value")
// 调用下一个处理器 / Call next handler
return next.RoundTrip(req)
})
func (RoundTripperFunc) RoundTrip ¶
RoundTrip 实现 http.RoundTripper 接口 RoundTrip implements the http.RoundTripper interface
参数 / Parameters:
- r: HTTP 请求 / HTTP request
返回值 / Returns:
- *http.Response: HTTP 响应 / HTTP response
- error: 错误信息 / Error
说明 / Notes:
- 直接调用底层函数完成请求发送和响应接收
- Directly calls the underlying function to complete request/response
type ServeMux ¶
type ServeMux struct {
// contains filtered or unexported fields
}
ServeMux 是 HTTP 请求路由多路复用器 ServeMux is an HTTP request router and multiplexer
核心特性 / Core Features:
- 基于前缀树(Trie)的高效路由匹配 / Efficient routing based on Trie tree
- 支持中间件链 / Supports middleware chain
- 支持路径级别的配置 / Supports path-level configuration
- 兼容 net/http.ServeMux / Compatible with net/http.ServeMux
- 支持所有 HTTP 方法 / Supports all HTTP methods
设计模式 / Design Pattern:
- 责任链模式(Middleware)/ Chain of Responsibility (Middleware)
- 组合模式(Node Tree)/ Composite Pattern (Node Tree)
示例 / Example:
mux := requests.NewServeMux(
requests.URL("0.0.0.0:8080"),
requests.Use(loggingMiddleware),
)
mux.Route("/", homeHandler)
mux.GET("/users", getUsersHandler)
mux.POST("/users", createUserHandler)
requests.ListenAndServe(context.Background(), mux)
func NewServeMux ¶
NewServeMux 创建一个新的路由多路复用器 NewServeMux creates a new HTTP request router
参数 / Parameters:
- opts: 配置选项(会话级别)/ Configuration options (session-level)
返回值 / Returns:
- *ServeMux: 路由器实例 / Router instance
示例 / Example:
// 基础路由器
// Basic router
mux := requests.NewServeMux()
// 带中间件的路由器
// Router with middleware
mux := requests.NewServeMux(
requests.URL("0.0.0.0:8080"),
requests.Use(loggingMiddleware, authMiddleware),
)
func (*ServeMux) CONNECT ¶
CONNECT 注册一个 CONNECT 请求处理器 CONNECT registers a handler for CONNECT requests
func (*ServeMux) DELETE ¶
DELETE 注册一个 DELETE 请求处理器 DELETE registers a handler for DELETE requests
示例 / Example:
mux.DELETE("/api/users/:id", deleteUserHandler)
func (*ServeMux) GET ¶
GET 注册一个 GET 请求处理器 GET registers a handler for GET requests
参数 / Parameters:
- path: 路由路径 / Route path
- v: 处理器 / Handler
- opts: 配置选项 / Configuration options
示例 / Example:
mux.GET("/api/users", getUsersHandler)
func (*ServeMux) Handle ¶
Handle 注册一个 http.Handler 到指定路径 Handle registers an http.Handler for the given path
参数 / Parameters:
- path: 路由路径 / Route path
- h: HTTP处理器 / HTTP handler
- opts: 配置选项 / Configuration options
示例 / Example:
mux.Handle("/static", http.FileServer(http.Dir("./public")))
func (*ServeMux) HandleFunc ¶
func (mux *ServeMux) HandleFunc(path string, f func(http.ResponseWriter, *http.Request), opts ...Option)
HandleFunc 注册一个处理函数到指定路径 HandleFunc registers a handler function for the given path
参数 / Parameters:
- path: 路由路径 / Route path
- f: 处理函数 / Handler function
- opts: 配置选项(可指定HTTP方法)/ Configuration options (can specify HTTP method)
注意 / Notes:
- 路径不能覆盖,如果路径不工作,可能是已经存在
- Paths cannot be overridden; if a path doesn't work, it may already exist
示例 / Example:
mux.HandleFunc("/api/users", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Users list")
}, requests.Method("GET"))
func (*ServeMux) OPTIONS ¶
OPTIONS 注册一个 OPTIONS 请求处理器 OPTIONS registers a handler for OPTIONS requests
func (*ServeMux) POST ¶
POST 注册一个 POST 请求处理器 POST registers a handler for POST requests
示例 / Example:
mux.POST("/api/users", createUserHandler)
func (*ServeMux) PUT ¶
PUT 注册一个 PUT 请求处理器 PUT registers a handler for PUT requests
示例 / Example:
mux.PUT("/api/users/:id", updateUserHandler)
func (*ServeMux) Pprof ¶
func (mux *ServeMux) Pprof()
Pprof 启用性能分析接口(用于调试) Pprof enables performance profiling endpoints (for debugging)
说明 / Notes:
- 必须访问 /debug/pprof/ 路径 / Must access /debug/pprof/ path
- 生产环境慎用 / Use with caution in production
可用的分析接口 / Available Profiling Endpoints:
- /debug/pprof/ - 主页 / Home page
- /debug/pprof/cmdline - 命令行参数 / Command line arguments
- /debug/pprof/profile - CPU性能分析 / CPU profiling
- /debug/pprof/symbol - 符号表 / Symbol table
- /debug/pprof/trace - 执行追踪 / Execution trace
示例 / Example:
mux := requests.NewServeMux() mux.Pprof() // 启用性能分析 / Enable profiling requests.ListenAndServe(context.Background(), mux) // 访问: http://localhost:8080/debug/pprof/
func (*ServeMux) Print ¶
Print 打印路由树结构(用于调试) Print prints the routing tree structure (for debugging)
func (*ServeMux) Redirect ¶
Redirect 设置路径重定向 Redirect sets up a redirect from source to target path
参数 / Parameters:
- source: 源路径 / Source path
- target: 目标路径 / Target path
说明 / Notes:
- 使用 301 永久重定向 / Uses 301 Moved Permanently
示例 / Example:
mux.Redirect("/old-path", "/new-path")
func (*ServeMux) Route ¶
Route 注册任意类型的处理器到指定路径 Route registers any type of handler for the given path
参数 / Parameters:
- path: 路由路径 / Route path
- v: 处理器(支持多种类型)/ Handler (supports multiple types)
- opts: 配置选项 / Configuration options
支持的处理器类型 / Supported Handler Types:
- http.HandlerFunc
- http.Handler
- func(http.ResponseWriter, *http.Request)
示例 / Example:
mux.Route("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Home")
})
mux.Route("/static", http.FileServer(http.Dir("./public")))
func (*ServeMux) ServeHTTP ¶
func (mux *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP 实现 http.Handler 接口 ServeHTTP implements the http.Handler interface
处理流程 / Processing Flow:
- 路由匹配:在路由树中查找最长匹配 / Route matching: find longest match in routing tree
- 路由校验:不存在则返回 404 / Route validation: return 404 if not exists
- 方法校验:方法不支持则返回 405 / Method validation: return 405 if method not supported
- 中间件链:按注册顺序应用中间件 / Middleware chain: apply middleware in registration order
- 执行处理器:调用最终的处理函数 / Execute handler: call final handler function
参数 / Parameters:
- w: 响应写入器 / Response writer
- r: HTTP 请求 / HTTP request
示例 / Example:
mux := requests.NewServeMux()
mux.Route("/api/users", handler)
http.ListenAndServe(":8080", mux) // mux 实现了 http.Handler
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server 是 HTTP 服务器封装 Server is an HTTP server wrapper
功能 / Features:
- 优雅关闭 / Graceful shutdown
- 支持 HTTP 和 HTTPS / Supports HTTP and HTTPS
- 可配置超时 / Configurable timeouts
- 生命周期回调 / Lifecycle callbacks
示例 / Example:
mux := requests.NewServeMux()
server := requests.NewServer(ctx, mux,
requests.URL("0.0.0.0:8080"),
requests.OnStart(func(s *http.Server) {
log.Printf("Server started on %s", s.Addr)
}),
)
server.ListenAndServe()
func NewServer ¶
NewServer 创建一个新的 HTTP 服务器 NewServer creates a new HTTP server
参数 / Parameters:
- ctx: 上下文(用于优雅关闭)/ Context (for graceful shutdown)
- h: HTTP 处理器 / HTTP handler
- opts: 配置选项(不会添加到 ServeMux)/ Configuration options (not added to ServeMux)
返回值 / Returns:
- *Server: 服务器实例 / Server instance
注意 / Notes:
- 会自动在 ctx.Done() 时优雅关闭服务器
- Will automatically shutdown gracefully when ctx.Done()
- opts 不会传递给 ServeMux,仅用于服务器配置
- opts are not passed to ServeMux, only for server configuration
示例 / Example:
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
mux := requests.NewServeMux()
server := requests.NewServer(ctx, mux,
requests.URL("0.0.0.0:8080"),
requests.Timeout(30*time.Second),
)
server.ListenAndServe()
func (*Server) ListenAndServe ¶
ListenAndServe 启动 HTTP 或 HTTPS 服务器并监听请求 ListenAndServe starts the HTTP or HTTPS server and listens for requests
功能说明 / Functionality:
- 在 TCP 网络地址 srv.Addr 上监听 / Listens on TCP network address srv.Addr
- 根据是否配置证书自动选择 HTTP 或 HTTPS / Automatically selects HTTP or HTTPS based on cert configuration
- 启用 TCP keep-alive / Enables TCP keep-alives for accepted connections
- 阻塞直到服务器关闭 / Blocks until server shutdown
HTTP vs HTTPS:
- 如果设置了 certFile 和 keyFile,启动 HTTPS 服务器
- If certFile and keyFile are set, starts HTTPS server
- 否则启动 HTTP 服务器
- Otherwise starts HTTP server
返回值 / Returns:
- error: 总是返回非 nil 错误,服务器关闭后返回 ErrServerClosed
- error: Always returns a non-nil error; returns ErrServerClosed after shutdown
示例 / Example:
// HTTP 服务器
// HTTP server
mux := requests.NewServeMux(requests.URL("0.0.0.0:8080"))
server := requests.NewServer(ctx, mux)
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
}
// HTTPS 服务器
// HTTPS server
mux := requests.NewServeMux(
requests.URL("0.0.0.0:443"),
requests.CertKey("cert.pem", "key.pem"),
)
server := requests.NewServer(ctx, mux)
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
}
func (*Server) Shutdown ¶
Shutdown 优雅地关闭服务器,不中断活动连接 Shutdown gracefully shuts down the server without interrupting any active connections
参数 / Parameters:
- ctx: 上下文 / Context
返回值 / Returns:
- error: 关闭过程中的错误 / Error during shutdown
说明 / Notes:
- 会等待 ctx.Done() 信号 / Waits for ctx.Done() signal
- 不会强制中断正在处理的请求 / Won't forcefully interrupt active requests
示例 / Example:
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() server.Shutdown(ctx)
type ServerSentEvents ¶
type ServerSentEvents struct {
// contains filtered or unexported fields
}
ServerSentEvents 实现了Server-Sent Events (SSE)流式传输的http.ResponseWriter包装器 它在标准ResponseWriter基础上提供SSE特定的功能
ServerSentEvents implements http.Handler interface for Server-Sent Events (SSE) streaming It wraps a http.ResponseWriter to provide SSE-specific functionality
SSE协议规范 / SSE Protocol Specification:
- 使用"text/event-stream"内容类型 / Uses "text/event-stream" content type
- 每个事件由一个或多个字段组成 / Each event consists of one or more fields
- 字段格式:name:value\n / Field format: name:value\n
- 空行表示事件结束 / Empty line marks event completion
使用场景 / Use Cases:
- 实时通知推送 / Real-time notification push
- 服务器到客户端的单向数据流 / One-way data stream from server to client
- 聊天应用消息推送 / Chat application message push
- 实时日志流 / Real-time log streaming
func (*ServerSentEvents) End ¶
func (s *ServerSentEvents) End()
End 通过写入两个换行符来终止SSE流 当流完成时应该调用此方法
End terminates the SSE stream by writing two newlines This should be called when the stream is complete
func (*ServerSentEvents) Header ¶
func (s *ServerSentEvents) Header() http.Header
Header 实现http.ResponseWriter接口,返回将要被WriteHeader发送的响应头
Header implements http.ResponseWriter interface It returns the header map that will be sent by WriteHeader
返回值 / Returns:
- http.Header: 响应头映射 / Response header map
func (*ServerSentEvents) Read ¶
func (s *ServerSentEvents) Read(b []byte) ([]byte, error)
Read 从给定的字节切片中解析SSE消息 处理不同类型的SSE事件(空行、事件类型、数据)
Read parses an SSE message from the given byte slice It handles different types of SSE events (empty, event, data)
参数 / Parameters:
- b: []byte - 原始SSE消息行 / Raw SSE message line
返回值 / Returns:
- []byte: 事件数据(仅对data事件) / Event data (only for data events)
- error: 解析错误 / Parsing error
返回逻辑 / Return Logic:
- data事件:返回事件值 / For data events: returns the event value
- 空行或event行:返回nil, nil / For empty or event lines: returns nil, nil
- 未知事件:返回nil和错误 / For unknown events: returns nil and an error
func (*ServerSentEvents) Send ¶
func (s *ServerSentEvents) Send(name string, b []byte) (int, error)
Send 向SSE流中写入一个命名的事件,并自动刷新响应 格式:name:value\n
Send writes a named SSE event with formatted data to the stream It automatically flushes the response after writing
参数 / Parameters:
- name: string - 事件名称(例如:"data", "event", "id", "retry"等) / Event name (e.g., "data", "event", "id", "retry", etc.)
- b: []byte - 事件数据 / Event data
返回值 / Returns:
- int: 写入的字节数 / Number of bytes written
- error: 写入错误 / Write error
示例 / Example:
// 发送数据事件
// Send data event
sse.Send("data", []byte(`{"message": "hello"}`))
// 发送自定义事件类型
// Send custom event type
sse.Send("event", []byte("user-login"))
sse.Send("data", []byte(`{"user": "alice"}`))
func (*ServerSentEvents) Write ¶
func (s *ServerSentEvents) Write(b []byte) (int, error)
Write 实现http.ResponseWriter接口,将字节切片作为data事件写入SSE流 这是一个便捷方法,相当于调用 Send("data", b)
Write implements http.ResponseWriter interface It writes the byte slice as a data event to the SSE stream
参数 / Parameters:
- b: []byte - 要发送的数据 / Data to send
返回值 / Returns:
- int: 写入的字节数 / Number of bytes written
- error: 写入错误 / Write error
func (*ServerSentEvents) WriteHeader ¶
func (s *ServerSentEvents) WriteHeader(statusCode int)
WriteHeader 实现http.ResponseWriter接口,写入HTTP响应状态码
WriteHeader implements http.ResponseWriter interface It writes the HTTP status code to the response
参数 / Parameters:
- statusCode: int - HTTP状态码 / HTTP status code
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session 是 HTTP 客户端会话管理器 Session is the HTTP client session manager
核心特性 / Core Features:
- 线程安全:可被多个goroutine并发使用 / Thread-safe: can be used concurrently by multiple goroutines
- 连接复用:自动管理连接池,提高性能 / Connection reuse: automatic connection pooling for better performance
- 配置持久化:会话级别的配置对所有请求生效 / Configuration persistence: session-level config applies to all requests
- 中间件支持:灵活的请求/响应处理链 / Middleware support: flexible request/response processing chain
设计原则 / Design Principles:
- 应该只创建一次并重复使用(遵循 net/http 的最佳实践)
- Should be created once and reused (follows net/http best practices)
- 每个会话维护独立的连接池和配置
- Each session maintains independent connection pool and configuration
示例 / Example:
// 创建一个会话,配置公共参数
// Create a session with common configuration
sess := requests.New(
requests.URL("https://api.example.com"),
requests.Header("Authorization", "Bearer token123"),
requests.Timeout(30*time.Second),
)
// 所有请求都会继承会话配置
// All requests will inherit session configuration
resp1, _ := sess.DoRequest(context.Background(), requests.Path("/users"))
resp2, _ := sess.DoRequest(context.Background(), requests.Path("/posts"))
func New ¶
New 创建一个新的会话实例 New creates a new session instance
参数 / Parameters:
- opts: 可选的配置选项(会话级别)/ Optional configuration options (session-level)
返回值 / Returns:
- *Session: 初始化的会话对象 / Initialized session object
配置说明 / Configuration Notes:
- 会话级配置对所有请求生效 / Session-level config applies to all requests
- 请求级配置可以覆盖会话配置 / Request-level config can override session config
示例 / Example:
// 基础会话
// Basic session
sess := requests.New()
// 带配置的会话
// Session with configuration
sess := requests.New(
requests.URL("https://api.example.com"),
requests.Header("User-Agent", "MyApp/1.0"),
requests.Timeout(30*time.Second),
requests.MaxConns(100),
)
func (*Session) Do ¶
Do 发送请求并返回标准的 http.Response Do sends a request and returns standard http.Response
重要提示 / Important Note:
- 必须手动关闭 resp.Body! / Must manually close resp.Body!
- 建议使用 DoRequest 方法,它会自动处理 Body 关闭
- Recommend using DoRequest method, which auto-handles Body closing
参数 / Parameters:
- ctx: 请求上下文 / Request context
- opts: 请求级别的配置选项(可覆盖会话配置)/ Request-level options (can override session config)
返回值 / Returns:
- *http.Response: HTTP 响应对象(需要手动关闭Body)/ HTTP response object (Body must be closed manually)
- error: 请求过程中的错误 / Error during request
示例 / Example:
resp, err := sess.Do(context.Background(),
requests.MethodPost,
requests.Path("/api/users"),
requests.Body(`{"name": "John"}`),
)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close() // 必须手动关闭! / Must close manually!
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
func (*Session) DoRequest ¶
DoRequest 发送请求并返回增强的 Response 对象 DoRequest sends a request and returns enhanced Response object
相比 Do 方法的优势 / Advantages over Do method:
- 自动安全关闭 resp.Body / Automatically and safely closes resp.Body
- 自动缓存响应内容到 Content / Auto-caches response content to Content
- 记录请求耗时和统计信息 / Records request duration and statistics
- 支持多次读取响应内容 / Supports multiple reads of response content
- 无需担心资源泄漏 / No need to worry about resource leaks
参数 / Parameters:
- ctx: 请求上下文 / Request context
- opts: 请求级别的配置选项 / Request-level configuration options
返回值 / Returns:
- *Response: 增强的响应对象(Content已缓存)/ Enhanced response object (Content cached)
- error: 请求过程中的错误 / Error during request
推荐使用场景 / Recommended Use Cases:
- 大多数日常HTTP请求 / Most daily HTTP requests
- 需要记录请求统计信息 / Need to record request statistics
- 需要多次读取响应内容 / Need to read response content multiple times
示例 / Example:
sess := requests.New(requests.URL("https://api.example.com"))
resp, err := sess.DoRequest(context.Background(),
requests.MethodPost,
requests.Path("/users"),
requests.Body(map[string]string{"name": "John"}),
)
if err != nil {
log.Fatal(err)
}
// 无需关闭Body,Content已自动缓存
// No need to close Body, Content is auto-cached
fmt.Println(resp.Content.String())
// 可以多次读取
// Can read multiple times
var user User
resp.JSON(&user)
// 查看统计信息
// View statistics
fmt.Printf("Request took %v\n", resp.Cost)
func (*Session) HTTPClient ¶
HTTPClient 返回配置好的 http.Client 实例 HTTPClient returns the configured http.Client instance
参数 / Parameters:
- opts: 可选的额外配置选项 / Optional additional configuration options
返回值 / Returns:
- *http.Client: 配置好的HTTP客户端 / Configured HTTP client
使用场景 / Use Cases:
- 需要使用标准库的 http.Client 接口 / Need to use standard library's http.Client interface
- 与其他库集成时 / When integrating with other libraries
func (*Session) RoundTrip ¶
RoundTrip 实现 http.RoundTripper 接口 RoundTrip implements the http.RoundTripper interface
这使得 Session 可以作为 http.Client 的 Transport 使用 This allows Session to be used as http.Client's Transport
参数 / Parameters:
- r: HTTP 请求对象 / HTTP request object
返回值 / Returns:
- *http.Response: HTTP 响应对象 / HTTP response object
- error: 请求过程中的错误 / Error during request
func (*Session) RoundTripper ¶
func (s *Session) RoundTripper(opts ...Option) http.RoundTripper
RoundTripper 返回配置好的 http.RoundTripper RoundTripper returns the configured http.RoundTripper
功能 / Features:
- 应用所有注册的中间件(按注册顺序的反序)/ Applies all registered middleware (in reverse order of registration)
- 支持中间件链式调用 / Supports middleware chaining
参数 / Parameters:
- opts: 可选的额外配置选项 / Optional additional configuration options
返回值 / Returns:
- http.RoundTripper: 配置好的 RoundTripper(包含中间件链)/ Configured RoundTripper (with middleware chain)
使用场景 / Use Cases:
- 需要自定义请求/响应处理逻辑 / Need custom request/response processing logic
- 与其他库集成时 / When integrating with other libraries
func (*Session) Transport ¶
Transport 返回底层的 http.Transport 实例 Transport returns the underlying http.Transport instance
返回值 / Returns:
- *http.Transport: 传输层对象 / Transport object
使用场景 / Use Cases:
- 需要访问或修改传输层配置 / Need to access or modify transport configuration
- 需要获取连接池状态 / Need to get connection pool status
type Stat ¶
type Stat struct {
// RequestId 请求唯一标识符,用于跟踪和关联请求
// RequestId is the unique identifier for request tracking and correlation
RequestId string `json:"RequestId"`
// StartAt 请求开始时间,格式为 "2006-01-02 15:04:05.000"
// StartAt is the request start time in format "2006-01-02 15:04:05.000"
StartAt string `json:"StartAt"`
// Cost 请求总耗时,单位:毫秒
// Cost is the total request duration in milliseconds
Cost int64 `json:"Cost"`
// Request 包含请求相关的所有信息
// Request contains all request-related information
Request struct {
// RemoteAddr 远程地址(仅服务器端使用)
// 客户端请求时此字段为空
// RemoteAddr is the remote address (server side only)
// For client requests, this field is unused
RemoteAddr string `json:"RemoteAddr"`
// URL 请求的URL地址
// 客户端:完整的请求地址,包含 schema://ip:port/path/xx
// 服务器端:仅包含路径,例如:/api/v1/xxx
// URL is the request URL
// Client: Full request address containing schema://ip:port/path/xx
// Server: Only path, e.g., /api/v1/xxx
URL string `json:"URL"`
// Method HTTP请求方法(GET, POST, PUT, DELETE等)
// Method is the HTTP request method (GET, POST, PUT, DELETE, etc.)
Method string `json:"Method"`
// Header 请求头信息(简化版,每个key只保留第一个value)
// Header is the request headers (simplified, only first value per key)
Header map[string]string `json:"Header"`
// Body 请求体内容(可能是字符串或JSON对象)
// Body is the request body content (may be string or JSON object)
Body any `json:"Body"`
} `json:"Request"`
// Response 包含响应相关的所有信息
// Response contains all response-related information
Response struct {
// URL 服务器地址,例如:http://127.0.0.1:8080(仅服务器端使用)
// 客户端请求时此字段为空
// URL is the server address, e.g., http://127.0.0.1:8080 (server side only)
// For client requests, this field is unused
URL string `json:"URL"`
// Header 响应头信息(简化版,每个key只保留第一个value)
// Header is the response headers (simplified, only first value per key)
Header map[string]string `json:"Header"`
// Body 响应体内容(可能是字符串或JSON对象)
// Body is the response body content (may be string or JSON object)
Body any `json:"Body"`
// StatusCode HTTP响应状态码
// StatusCode is the HTTP response status code
StatusCode int `json:"StatusCode"`
// ContentLength 响应体长度(字节)
// ContentLength is the response body length in bytes
ContentLength int64 `json:"ContentLength"`
} `json:"Response"`
// Err 错误信息(如果有)
// Err is the error message (if any)
Err string `json:"Err"`
}
Stat 是HTTP请求统计信息结构,记录了请求和响应的完整信息 该结构在客户端和服务器端都可以使用,但某些字段的含义略有不同
Stat is the HTTP request statistics structure that records complete request and response information This structure can be used on both client and server side, but some fields have slightly different meanings
使用场景 / Use Cases:
- 性能监控和分析 / Performance monitoring and analysis
- 请求日志记录 / Request logging
- 调试和故障排查 / Debugging and troubleshooting
- API调用统计 / API call statistics
示例 / Example:
// 客户端获取统计信息
// Client getting statistics
resp, _ := session.DoRequest(ctx, requests.URL("http://example.com"))
stat := resp.Stat()
fmt.Printf("Request took %dms\n", stat.Cost)
// 服务器端使用Setup中间件记录统计
// Server using Setup middleware to record statistics
mux := requests.NewServeMux()
mux.Use(requests.Setup(func(ctx context.Context, stat *requests.Stat) {
log.Printf("Request: %s %s - %dms", stat.Request.Method, stat.Request.URL, stat.Cost)
}))
func (*Stat) Print ¶
Print 返回格式化的日志字符串(主要用于服务器端) 输出格式:时间 方法 "客户端地址 -> 服务器地址+路径" - 状态码 响应大小 耗时
Print returns a formatted log string (mainly used for server side) Format: Time Method "ClientAddr -> ServerAddr+Path" - StatusCode ResponseSize Duration
返回值 / Returns:
- string: 格式化的日志字符串 / Formatted log string
示例 / Example:
// 服务器端日志输出示例 // Server side log output example // 2024-01-01 12:00:00.000 POST "192.168.1.100:8080 -> http://127.0.0.1:8080/api/v1/users" - 200 1024B in 150ms log.Println(stat.Print())
func (*Stat) RequestBody ¶
RequestBody 返回请求体内容的字符串表示
RequestBody returns the request body content as a string ¶
返回值 / Returns:
- string: 请求体的字符串表示(JSON格式) / String representation of request body (JSON format)
示例 / Example:
stat := resp.Stat()
fmt.Printf("Request body: %s\n", stat.RequestBody())
func (*Stat) ResponseBody ¶
ResponseBody 返回响应体内容的字符串表示
ResponseBody returns the response body content as a string ¶
返回值 / Returns:
- string: 响应体的字符串表示(JSON格式) / String representation of response body (JSON format)
示例 / Example:
stat := resp.Stat()
fmt.Printf("Response body: %s\n", stat.ResponseBody())
func (*Stat) String ¶
String 实现 fmt.Stringer 接口,将Stat对象序列化为JSON字符串
String implements the fmt.Stringer interface, serializes Stat object to JSON string ¶
返回值 / Returns:
- string: JSON格式的统计信息字符串 / JSON formatted statistics string
示例 / Example:
stat := resp.Stat() fmt.Println(stat.String()) // 输出完整的JSON格式统计信息 / Output full JSON statistics