httpx

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2025 License: MIT Imports: 12 Imported by: 3

README

httpx: Minimalist HTTP Extensions for Go

Go Report Card

中文 | English

httpx is a set of HTTP extension tools based on Go 1.18+ generics. It is not a heavy web framework, but a powerful enhancement for the standard library net/http.

It aims to eliminate repetitive JSON decoding, parameter validation, and response encapsulation code in http.Handler through Generics, while maintaining full compatibility with the standard library.

Core Concepts

  1. Type Safety: Leveraging generics to transform func(w, r) into strongly typed func(ctx, *Req) (*Res, error).
  2. Convention over Configuration: Provides standard JSON response envelopes, error handling, and log formats out of the box.
  3. Performance at Scale: Provides a SelfValidatable interface to bypass reflection validation; integrates httpsnoop for zero-overhead metric capture.

Installation

go get github.com/oy3o/httpx

Quick Start

1. Define Request & Response

Use json tags to define the structure and validate tags to define validation rules.

type LoginReq struct {
    Username string `json:"username" validate:"required,min=3"`
    Password string `json:"password" validate:"required"`
}

type LoginRes struct {
    Token string `json:"token"`
    User  string `json:"user_id"`
}
2. Write Business Logic

No need to manipulate http.ResponseWriter and *http.Request. Just focus on inputs and outputs.

func LoginHandler(ctx context.Context, req *LoginReq) (*LoginRes, error) {
    if req.Username == "admin" && req.Password == "123456" {
        return &LoginRes{Token: "abc-123", User: "1"}, nil
    }
    // Return an error, httpx will automatically map it to an HTTP status code
    return nil, &httpx.HttpError{Code: 401, Msg: "Invalid credentials"}
}
3. Register Routes

Use httpx.NewHandler to convert business functions into standard http.Handlers.

func main() {
    mux := http.NewServeMux()

    // Automatic processing: Bind -> Validate -> Logic -> Response
    mux.Handle("POST /login", httpx.NewHandler(LoginHandler))

    // Add middleware: Recovery -> Logger -> CORS -> Handler
    handler := httpx.Chain(mux, 
        httpx.Recovery(nil),
        httpx.Logger(nil),
        httpx.DefaultCORS(),
    )

    http.ListenAndServe(":8080", handler)
}

Example Response:

{
    "code": 0,
    "message": "ok",
    "data": {
        "token": "abc-123",
        "user_id": "1"
    }
}

Core Features

1. Smart Binding

httpx.Bind automatically selects the parsing strategy based on the request headers:

  • GET: Parses URL Query parameters.
  • Content-Type: application/json: Parses JSON Body.
  • Content-Type: multipart/form-data: Parses forms (supports file uploads).
2. Hybrid Validation

To balance development efficiency and runtime performance, httpx supports two validation modes:

  • Reflection Mode (Slow Path): Uses struct tags (validate:"required"). Fast development, but incurs reflection overhead.
  • Interface Mode (Fast Path): Implements the SelfValidatable interface. Completely reflection-free, suitable for high-traffic endpoints.
// Fast Validation: httpx calls this method first, skipping reflection
func (r *LoginReq) Validate(ctx context.Context) error {
    if len(r.Username) < 3 {
        return errors.New("username too short")
    }
    return nil
}
3. Unified Error Handling

Any return value implementing the error interface will be captured. If the ErrorCoder interface is implemented, the specified HTTP status code is returned.

// Predefined error
return nil, httpx.ErrBadRequest

// Custom status code
return nil, &httpx.HttpError{Code: 429, Msg: "Slow down"}
4. Flexible Response Options
  • Standard Mode: Default wrapper in {code, msg, data}.
  • No Envelope Mode: Use the httpx.NoEnvelope() option to return data directly (suitable for standard protocols like OAuth).
  • Streamable Response: Return values implementing the Streamable interface (e.g., FileResponse) handle file downloads or streaming writes automatically.

Middleware Ecosystem

httpx provides a set of middleware based on standard library interfaces:

Middleware Description
Chain Composes multiple middleware into an onion model.
Recovery Captures Panics to prevent service crashes; supports custom Hooks.
Logger Based on httpsnoop, accurately records status codes and latency; compatible with WebSocket/SSE.
CORS Flexible Cross-Origin Resource Sharing configuration.
RateLimit Simple rate limiting interface integration.
AuthBearer Standard Bearer Token authentication extraction.
AuthBasic Standard Basic Auth authentication extraction.

Best Practices

It is recommended to use httpx with netx (network layer extensions) and o11y (observability) to build complete Go services:

// server/run.go
func Run() {
    // 1. Network Layer (netx)
    ln := netx.Listen(":8080") 
    
    // 2. Application Layer (httpx)
    h := httpx.NewHandler(MyLogic)
    
    // 3. Start
    http.Serve(ln, h)
}

Documentation

Index

Constants

View Source
const IdentityKey contextKey = "identity"

Variables

View Source
var (
	ErrBadRequest = &HttpError{400, "Bad Request"}
	ErrValidation = &HttpError{400, "Validation Failed"}
	ErrInternal   = &HttpError{500, "Internal Server Error"}
)

预定义错误

View Source
var Decoder = schema.NewDecoder()
View Source
var ErrorHook func(ctx context.Context, err error) = nil

ErrorHook 是一个回调函数,用于处理错误的副作用(如记录日志)。

View Source
var GetTraceID func(ctx context.Context) string = nil

GetTraceID 是一个钩子变量,允许外部注入获取 TraceID 的逻辑

View Source
var Validator = validator.New()

Functions

func Bind

func Bind(r *http.Request, v any) error

Bind 将请求数据绑定到 v,并进行参数验证 支持 JSON, Form (urlencoded/multipart), Query Param

func Chain

func Chain(h http.Handler, mws ...Middleware) http.Handler

Chain 组合多个中间件

func Error

func Error(w http.ResponseWriter, r *http.Request, err error)

Error 统一处理错误响应。

func GetIdentity

func GetIdentity(ctx context.Context) any

GetIdentity 从 Context 中获取身份信息。

func NewHandler

func NewHandler[Req any, Res any](fn HandlerFunc[Req, Res], opts ...Option) http.HandlerFunc

NewHandler 将强类型的业务函数转换为标准的 http.HandlerFunc。

func Validate

func Validate(ctx context.Context, v any) error

Types

type AuthValidator

type AuthValidator func(ctx context.Context, token string) (any, error)

AuthValidator 定义验证回调函数签名。 返回的 any 将被注入到 Context 中(例如 User 对象)。

type BasicValidator

type BasicValidator func(ctx context.Context, user, pass string) (any, error)

BasicValidator 定义 Basic Auth 验证回调。

type CORSOptions

type CORSOptions struct {
	AllowedOrigins   []string
	AllowedMethods   []string
	AllowedHeaders   []string
	ExposedHeaders   []string
	AllowCredentials bool
	MaxAge           int
}

CORSOptions 定义 CORS 配置

type ErrorCoder

type ErrorCoder interface {
	HTTPStatus() int
	error
}

ErrorCoder 是一个接口,允许 error 自定义 HTTP 状态码。

type FileResponse

type FileResponse struct {
	Content io.Reader
	Name    string
	Size    int64
	Type    string
}

FileResponse 是一个实现了 Streamable 的文件响应辅助类。

func (*FileResponse) Headers

func (f *FileResponse) Headers() map[string]string

func (*FileResponse) WriteTo

func (f *FileResponse) WriteTo(w io.Writer) (int64, error)

type HandlerFunc

type HandlerFunc[Req any, Res any] func(ctx context.Context, req *Req) (Res, error)

HandlerFunc 是业务逻辑的通用签名。 Req: 请求体结构体 (会自动 decode & validate) Res: 响应体结构体 (会自动 encode)

type HttpError

type HttpError struct {
	Code int
	Msg  string
}

HttpError 是一个简单的错误实现

func (*HttpError) Error

func (e *HttpError) Error() string

func (*HttpError) HTTPStatus

func (e *HttpError) HTTPStatus() int

type Limiter

type Limiter interface {
	Allow(r *http.Request) bool
}

Limiter 接口定义了限流器的行为。 Allow 应该非阻塞地返回是否允许请求。

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware 标准中间件定义

func AuthBasic

func AuthBasic(validator BasicValidator) Middleware

AuthBasic Basic Auth 认证中间件。

func AuthBearer

func AuthBearer(validator AuthValidator) Middleware

AuthBearer Bearer Token 认证中间件。

func CORS

func CORS(opts CORSOptions) Middleware

CORS 跨域资源共享中间件。

func DefaultCORS

func DefaultCORS() Middleware

DefaultCORS 返回一个宽容的 CORS 中间件(开发环境常用)。

func Logger

func Logger(logFunc func(duration time.Duration, status int, path string)) Middleware

Logger 使用 httpsnoop 包装 ResponseWriter,确保兼容 Flusher/Hijacker

func RateLimit

func RateLimit(limiter Limiter) Middleware

RateLimit 返回一个限流中间件。

func Recovery

func Recovery(panicHook func(ctx context.Context, err interface{})) Middleware

Recovery 捕获 Panic 防止服务崩溃

type Option

type Option func(*config)

func NoEnvelope

func NoEnvelope() Option

NoEnvelope 指示 Handler 不要使用标准的 {code, msg, data} 封口, 而是直接将 Res 序列化为 JSON。适用于 OAuth 等标准协议。

type Response

type Response[T any] struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    T      `json:"data,omitempty"`
	TraceID string `json:"trace_id,omitempty"`
}

Response 是默认的统一响应信封。

type SelfValidatable

type SelfValidatable interface {
	Validate(ctx context.Context) error
}

SelfValidatable 是高性能验证接口。 如果 Request 结构体实现了此接口,将跳过反射验证。

type Streamable

type Streamable interface {
	Headers() map[string]string
	WriteTo(w io.Writer) (int64, error)
}

Streamable 接口用于指示该结构体是流式响应(文件下载、SSE)。

Jump to

Keyboard shortcuts

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