webx

package module
v2.2.1 Latest Latest
Warning

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

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

README

webx

基于 Go 标准库的工业级 HTTP/HTTPS 服务组件库: 路由、上下文、中间件链全部自研,传输层基于 net/http

Go Version License

当前状态:v2.0.0 已发布(破坏性变更)。各包语句覆盖率 100%, 三平台 CI + race + fuzz + apidiff 全绿。

模块路径:github.com/lcylpzls/webx/v2(v2 主版本规范)。

技术栈

组件 用途 说明
Go 标准库 net/http HTTP/1.1、HTTP/2、路由、生命周期 唯一运行时基座
logx 结构化日志 自家库,零第三方依赖
errx 结构化错误 自家库,统一错误码
confx TOML 配置加载 自家库
quic-go HTTP/3 (QUIC) 传输 第三方直接依赖之一
google/uuid UUID v7 请求 ID 标准实现,uuid.Must 稳定生成
metricsx(可选) 统一外置指标底座 仅示例接入,库本体不依赖

第三方直接依赖:quic-go(HTTP/3)与 google/uuid(UUID v7),其余全部自研。

快速开始

  1. 复制 config.example.tomlconfig.toml,填入 TLS 证书路径并按需修改;
  2. examples/basic 起步体验最小服务;
  3. 生产部署直接参考 examples/production: 探针、可信代理、限流、并发限制、外置指标、上传与优雅关闭全配置模板。

设计原则

  • 零泄漏:不导出任何第三方类型,业务 Handler 只接触自研 *Context
  • 链式 API:Builder 风格配置,配置即文档;
  • 启动后不可变Start() 之后修改配置仅记录警告;
  • 绝不 panic:唯一 recover() 位于 Recovery 中间件;
  • 绝不吞错:所有错误路径返回 errx 结构化错误并记录日志;
  • 简体中文:日志、打印、注释、文档统一简体中文;
  • 工业级门槛:语句覆盖率 100%、fuzz、race、三平台 CI、API 基线。

功能清单

  • 🔒 强制 TLS:HTTP/2(TLS over TCP)+ HTTP/3(QUIC over UDP)+ Unix Socket 多通道同时监听;
  • 🔗 链式配置:路由、分组、中间件、限流、静态文件一键组装;
  • 🗺️ 路由::id / *filepath 参数语法、404/405 JSON、尾斜杠重定向;
  • 🧱 内置中间件:Recovery / RequestID / Timeout / CORS / Validation / RateLimit / Gzip / Metrics / AccessLog / Security / BodyLimit(顺序可配置);
  • 📤 文件上传:FormFile / SaveUploadedFile(沿用请求体大小限制);
  • 📏 全局请求体限制:max_body_bytes 超限直接 413;
  • 🛡️ 并发限制:SetMaxConcurrentRequests 超限返回 503 + Retry-After(防雪崩);
  • 🔐 浏览器安全基线:CSP、HSTS 全指令、COOP/CORP/COEP、Origin-Agent-Cluster、PNA;
  • 🐢 慢请求日志:slow_request_threshold 超阈值自动 Warn;
  • ⚡ 静态资源 ETag:可选弱 ETag,If-None-Match 命中返回 304;
  • 🕵️ 可信代理:trusted_proxies 配置,代理头防伪造(限流/审计/日志统一);
  • 📊 指标统一外置:WithMetrics(metricsx 实例) 转发请求/耗时/水位事件, 由 metricsx + promhttp 自行暴露;
  • ✏️ 错误文案可定制:error_messages 覆盖内置 404/405/413/429/503;
  • 📋 AccessLog 请求头白名单:access_log_headers + 复用脱敏;
  • 📊 标准化响应:{code, msg, data, requestId, timestamp}
  • 🩺 健康检查:/health,路径可配置;
  • 🔍 探针分离:/healthz 存活 / /readyz 就绪(优雅关闭中就绪自动 503);
  • 📈 v2 不再内置 /metrics 端点,指标采集职责完全交给外部底座;
  • 🪵 日志接入 logx;错误接入 errx;配置接入 confx(TOML);
  • 🧹 优雅关闭:SIGINT/SIGTERM 信号捕获 + Stop(ctx)
  • 🗂️ 静态文件服务与 SPA 回退(支持 embed)。

文档索引

性能数据(Benchmark 实测)

基准 结果
路由匹配+分发(500 条参数化路由) 0.10µs/op,0 allocs
HTTP/1.1 端到端(HTTPS,单核/多核) 35.3µs / 8.6µs
HTTP/2 端到端(HTTPS,单核/多核) 50.4µs / 12.3µs
HTTP/3 端到端(QUIC,单核/多核) 118.1µs / 29.9µs

与 gin / echo / fasthttp / hertz 的横向对比(HTTPS、单核/多核, 含 HTTP/2/HTTP/3 完整矩阵与方法学)见 benchmarks/BENCHMARKS.md

API 速查

能力 API
创建服务 webx.NewServer(cfg, logger)
加载配置 webx.LoadConfig("config.toml")
多通道监听 UseHttp2Listen / UseHttp3Listen / UseUnixSocketListen
路由/分组 RegisterRoute / RegisterRouteGroup / RouteGroup.GET...
中间件管理 UseGlobalMiddleware / OverrideMiddleware / Disable/EnableMiddleware
请求 ID SetRequestIDOptions(自定义头名与生成器,默认 UUID v7)
指标接入 WithMetrics(metricsx 实例)(请求/耗时/水位事件,可选)
并发限制 SetMaxConcurrentRequests(n)(超限 503 + Retry-After)
内置中间件 Recovery、RequestID、BodyLimit、Timeout、CORS、Validation、RateLimit、Gzip、Metrics、AccessLog、Security
标准化响应 c.Success / c.Fail / c.JSONResponse / c.AbortWithStatusJSON
参数绑定 c.BindJSON / c.BindForm / c.BindQuery
自动绑定 c.Bind(out)(按 Content-Type 自动分派 JSON/Form/Query)
嵌套绑定 form / query tag 支持嵌套结构体与结构体指针
文件上传 c.FormFile(name) / c.SaveUploadedFile(fh, dest)
Web 便捷方法 c.Redirect / c.Cookie / c.SetCookie / c.SetSecureCookie / c.File
errx 集成 webx.RespondError / StatusForError
健康检查 RegisterHealthCheck(/health 聚合输出)
存活/就绪探针 RegisterLivenessCheck(/healthz)/ RegisterReadinessCheck(/readyz)
静态/SPA ServeStaticDir / ServeStaticFS / ServeStatic*WithOptions(MaxAge/DisableIndex/EnableETag)/ EnableSPA
反向代理 webx/proxy.Handler(target, opts...)
代理选项 WithErrorHandler / WithTimeout / WithFlushInterval / WithDirector / WithModifyResponse
指标 Server.Metrics()(状态码分布、协议维度、路由/分组级聚合、活跃请求/连接、限流/Panic)
路由/分组统计 Server.RouteStats() / Server.GroupStats()
优雅关闭 Stop(ctx) / 信号自动关闭
证书热重载 SetCertificateLoader(默认按文件 mtime 自动重载)

浏览器安全基线

  • 已覆盖:X-Content-Type-OptionsX-Frame-OptionsReferrer-PolicyStrict-Transport-Security(max-age + includeSubDomains + preload)、 Permissions-PolicyCross-Origin-Opener-PolicyCross-Origin-Resource-PolicyCross-Origin-Embedder-PolicyContent-Security-Policy(含 Report-Only)、 Origin-Agent-Cluster、CORS Private Network Access;
  • 刻意不提供:X-XSS-ProtectionExpect-CT(已被现代浏览器废弃)。

平台限制

  • Windows 上使用 Unix Socket 监听要求 Windows 10 build 1803(10.0.17134) 或更高版本;低于该版本时 Start() 会拒绝初始化并返回 WEBX_START_FAILED

可观测性规范

  • webx 不内置分布式追踪(保持零第三方依赖定位);
  • 链路追踪统一使用 tracex 基座: s.UseGlobalMiddleware(txwebx.Middleware(m))
  • 全局中间件已覆盖 404/405 兜底请求,追踪无盲区;
  • X-Request-ID 请求 ID 能力保留,与链路追踪无关。

License

MIT © lcylpzls

Documentation

Overview

Package webx 提供基于 Go 标准库的工业级 HTTP/HTTPS 服务组件库。 路由基于自研 radix 匹配树,上下文与中间件链自研,日志/错误/配置 分别接入 logx / errx / confx,HTTP/3 使用 quic-go。

Index

Examples

Constants

View Source
const (
	CodeSuccess            = core.CodeSuccess
	CodeBadRequest         = core.CodeBadRequest
	CodeNotFound           = core.CodeNotFound
	CodeMethodNotAllowed   = core.CodeMethodNotAllowed
	CodeTooManyRequests    = core.CodeTooManyRequests
	CodeInternalError      = core.CodeInternalError
	CodeServiceUnavailable = core.CodeServiceUnavailable
)

标准化响应业务码。

View Source
const (
	// ErrorMessageNotFound 404 兜底文案。
	ErrorMessageNotFound = "not_found"
	// ErrorMessageMethodNotAllowed 405 兜底文案。
	ErrorMessageMethodNotAllowed = "method_not_allowed"
	// ErrorMessageBodyTooLarge 413 请求体过大文案。
	ErrorMessageBodyTooLarge = "body_too_large"
	// ErrorMessageRateLimited 429 限流拒绝文案。
	ErrorMessageRateLimited = "rate_limited"
	// ErrorMessageTooBusy 503 并发限制拒绝文案。
	ErrorMessageTooBusy = "too_busy"
	// ErrorMessageTimeout 503 请求超时文案。
	ErrorMessageTimeout = "timeout"
)

内置错误响应文案键(配合 Config.ErrorMessages / SetErrorMessages 覆盖)。

View Source
const (
	// CodeConfigInvalid 配置校验失败。
	CodeConfigInvalid errx.Code = "WEBX_CONFIG_INVALID"
	// CodeConfigLoadFailed 配置文件加载失败。
	CodeConfigLoadFailed errx.Code = "WEBX_CONFIG_LOAD_FAILED"
	// CodeListenFailed 监听器创建失败。
	CodeListenFailed errx.Code = "WEBX_LISTEN_FAILED"
	// CodeStartFailed 服务启动失败。
	CodeStartFailed errx.Code = "WEBX_START_FAILED"
	// CodeShutdownFailed 优雅关闭失败。
	CodeShutdownFailed errx.Code = "WEBX_SHUTDOWN_FAILED"
	// CodePanic 请求处理发生 panic(Recovery 中间件捕获)。
	CodePanic errx.Code = "WEBX_PANIC"
)

webx 错误码:统一使用 errx 结构化错误。

Variables

View Source
var NoMethodHandler = core.NoMethodHandler

NoMethodHandler 405 兜底处理器。

View Source
var NoRouteHandler = core.NoRouteHandler

NoRouteHandler 404 兜底处理器(嵌入自定义路由器时使用)。

Functions

func GracefulShutdown

func GracefulShutdown(
	ctx context.Context,
	logger logx.Logger,
	httpServer *http.Server,
	listener net.Listener,
	shutdownTimeout time.Duration,
	unixSocketPath string,
	cleanupFuncs []func(),
) error

GracefulShutdown 监听系统信号并执行优雅关闭。 收到 SIGINT/SIGTERM 后调用 httpServer.Shutdown 排空请求。

func RespondError

func RespondError(c *Context, err error)

RespondError 将 errx 错误映射为标准化错误响应。 状态码由 Kind 映射(如 KindNotFound → 404),响应体为统一 JSON 信封。

Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/lcylpzls/errx"
	"github.com/lcylpzls/webx/v2"
)

func main() {
	rec := httptest.NewRecorder()
	c := webx.NewContext(rec, httptest.NewRequest(http.MethodGet, "/", nil))
	webx.RespondError(c, errx.New(errx.KindNotFound, "USER_NOT_FOUND", "用户不存在"))
	fmt.Println(rec.Code)
}
Output:
404

func RespondErrorWithData

func RespondErrorWithData(c *Context, err error, data any)

RespondErrorWithData 将 errx 错误映射为标准化错误响应,并附带业务数据。

func StatusForError

func StatusForError(err error) int

StatusForError 返回 errx 错误对应的 HTTP 状态码;非 errx 错误返回 500。

Example
package main

import (
	"fmt"

	"github.com/lcylpzls/errx"
	"github.com/lcylpzls/webx/v2"
)

func main() {
	err := errx.New(errx.KindForbidden, "NO_PERMISSION", "无权限")
	fmt.Println(webx.StatusForError(err))
}
Output:
403

Types

type Config

type Config struct {
	// TLSCertFile TLS 证书文件路径(PEM 格式),必填。
	TLSCertFile string `toml:"tls_cert_file"`
	// TLSKeyFile TLS 私钥文件路径(PEM 格式),必填。
	TLSKeyFile string `toml:"tls_key_file"`
	// MinTLSVersion 最低 TLS 版本,0 表示默认 TLS 1.2(仅允许 TLS1.2/1.3)。
	MinTLSVersion uint16 `toml:"min_tls_version"`

	// ReadTimeout HTTP 读取超时时间。
	ReadTimeout time.Duration `toml:"read_timeout"`
	// WriteTimeout HTTP 写入超时时间。
	WriteTimeout time.Duration `toml:"write_timeout"`
	// ReadHeaderTimeout 请求头读取超时时间,0 表示默认 10s(Slowloris 防护)。
	ReadHeaderTimeout time.Duration `toml:"read_header_timeout"`
	// IdleTimeout HTTP 空闲连接超时时间。
	IdleTimeout time.Duration `toml:"idle_timeout"`
	// RequestTimeout 单个请求的超时时间,由 Timeout 中间件使用。
	RequestTimeout time.Duration `toml:"request_timeout"`
	// ShutdownTimeout 优雅关闭的最大等待时间。
	ShutdownTimeout time.Duration `toml:"shutdown_timeout"`
	// MaxHeaderBytes 请求头的最大字节数。
	MaxHeaderBytes int `toml:"max_header_bytes"`
	// MaxBodyBytes BindJSON 的最大请求体字节数,0 表示默认 10MB。
	MaxBodyBytes int64 `toml:"max_body_bytes"`
	// QUICMaxIdleTimeout HTTP/3 空闲连接超时,0 表示默认 30s。
	QUICMaxIdleTimeout time.Duration `toml:"quic_max_idle_timeout"`
	// QUICMaxIncomingStreams HTTP/3 单连接最大入站流数,0 表示默认 100。
	QUICMaxIncomingStreams int64 `toml:"quic_max_incoming_streams"`
	// QUICDrainTimeout HTTP/3 关闭前等待活动连接排空的时间,0 表示不等待。
	QUICDrainTimeout time.Duration `toml:"quic_drain_timeout"`

	// HealthPath 健康检查端点路径,默认为 "/health"。
	HealthPath string `toml:"health_path"`
	// LivenessPath 存活探针端点路径,默认为 "/healthz"。
	LivenessPath string `toml:"liveness_path"`
	// ReadinessPath 就绪探针端点路径,默认为 "/readyz"。
	ReadinessPath string `toml:"readiness_path"`
	// LogLevel 日志级别,可选 debug、info、warn、error,为空默认 info。
	LogLevel string `toml:"log_level"`
	// AccessLogEnabled 是否启用访问日志中间件。
	AccessLogEnabled bool `toml:"access_log_enabled"`
	// LogSuccessReq 访问日志是否记录成功请求(默认仅记录非 2xx)。
	LogSuccessReq bool `toml:"log_success_req"`
	// AccessLogSampleRate 访问日志采样率:0=全部记录,N>0 平均每 N 条记录 1 条。
	AccessLogSampleRate int `toml:"access_log_sample_rate"`
	// AccessLogRedact 访问日志 query 参数中需要脱敏的键。
	AccessLogRedact []string `toml:"access_log_redact"`
	// AccessLogHeaders 访问日志需要记录的请求头白名单。
	AccessLogHeaders []string `toml:"access_log_headers"`
	// TrustedProxies 可信代理网段(CIDR 或 IP);仅来自这些网段的请求
	// 才信任 X-Forwarded-For / X-Real-IP,空列表表示不信任任何代理头。
	TrustedProxies []string `toml:"trusted_proxies"`
	// SlowRequestThreshold 慢请求日志阈值(0=关闭)。
	SlowRequestThreshold time.Duration `toml:"slow_request_threshold"`

	// CORSAllowedOrigins CORS 允许的来源列表,为空使用默认值。
	CORSAllowedOrigins []string `toml:"cors_allowed_origins"`
	// CORSAllowedMethods CORS 允许的 HTTP 方法列表。
	CORSAllowedMethods []string `toml:"cors_allowed_methods"`
	// CORSAllowedHeaders CORS 允许的请求头列表。
	CORSAllowedHeaders []string `toml:"cors_allowed_headers"`
	// CORSExposeHeaders CORS 允许浏览器读取的响应头列表。
	CORSExposeHeaders []string `toml:"cors_expose_headers"`
	// CORSMaxAge CORS 预检请求的缓存时间。
	CORSMaxAge time.Duration `toml:"cors_max_age"`
	// CORSAllowCredentials 是否允许携带凭据。
	CORSAllowCredentials bool `toml:"cors_allow_credentials"`
	// CORSAllowPrivateNetwork 是否允许内网(Private Network Access)预检。
	CORSAllowPrivateNetwork bool `toml:"cors_allow_private_network"`

	// MiddlewareRequestID 是否启用 RequestID 中间件。
	MiddlewareRequestID bool `toml:"middleware_request_id"`
	// MiddlewareCORS 是否启用 CORS 中间件。
	MiddlewareCORS bool `toml:"middleware_cors"`
	// MiddlewareTimeout 是否启用 Timeout 中间件。
	MiddlewareTimeout bool `toml:"middleware_timeout"`
	// MiddlewareRecovery 是否启用 Recovery 中间件。
	MiddlewareRecovery bool `toml:"middleware_recovery"`
	// MiddlewareValidation 是否启用 Validation 中间件。
	MiddlewareValidation bool `toml:"middleware_validation"`
	// MiddlewareGzip 是否启用响应压缩中间件。
	MiddlewareGzip bool `toml:"middleware_gzip"`
	// MiddlewareMetrics 是否启用请求/5xx 计数中间件。
	MiddlewareMetrics bool `toml:"middleware_metrics"`
	// MiddlewareSecurity 是否启用安全响应头中间件。
	MiddlewareSecurity bool `toml:"middleware_security"`
	// SecurityHSTSMaxAge HSTS 缓存秒数(0=不启用 HSTS)。
	SecurityHSTSMaxAge int `toml:"security_hsts_max_age"`
	// SecurityReferrerPolicy Referrer-Policy 取值(空=不设置)。
	SecurityReferrerPolicy string `toml:"security_referrer_policy"`
	// SecurityPermissionsPolicy Permissions-Policy 取值(空=不设置)。
	SecurityPermissionsPolicy string `toml:"security_permissions_policy"`
	// SecurityCrossOriginOpenerPolicy Cross-Origin-Opener-Policy 取值(空=不设置)。
	SecurityCrossOriginOpenerPolicy string `toml:"security_cross_origin_opener_policy"`
	// SecurityCrossOriginResourcePolicy Cross-Origin-Resource-Policy 取值(空=不设置)。
	SecurityCrossOriginResourcePolicy string `toml:"security_cross_origin_resource_policy"`
	// SecurityCrossOriginEmbedderPolicy Cross-Origin-Embedder-Policy 取值(空=不设置)。
	SecurityCrossOriginEmbedderPolicy string `toml:"security_cross_origin_embedder_policy"`
	// SecurityContentSecurityPolicy Content-Security-Policy 取值(空=不设置)。
	SecurityContentSecurityPolicy string `toml:"security_content_security_policy"`
	// SecurityContentSecurityPolicyReportOnly Content-Security-Policy-Report-Only 取值(空=不设置)。
	SecurityContentSecurityPolicyReportOnly string `toml:"security_content_security_policy_report_only"`
	// SecurityHSTSIncludeSubDomains HSTS 指令附加 includeSubDomains。
	SecurityHSTSIncludeSubDomains bool `toml:"security_hsts_include_subdomains"`
	// SecurityHSTSPreload HSTS 指令附加 preload。
	SecurityHSTSPreload bool `toml:"security_hsts_preload"`
	// SecurityOriginAgentCluster 是否输出 Origin-Agent-Cluster: ?1。
	SecurityOriginAgentCluster bool `toml:"security_origin_agent_cluster"`
	// GzipMinSize 响应压缩最小字节数(0=默认 1024)。
	GzipMinSize int `toml:"gzip_min_size"`
	// GzipLevel 响应压缩级别(0=标准库默认,1-9 对应 BestSpeed-BestCompression)。
	GzipLevel int `toml:"gzip_level"`
	// Debug 调试模式:Recovery 响应携带 panic 摘要(生产环境保持 false)。
	Debug bool `toml:"debug"`
	// ErrorMessages 内置错误响应文案覆盖(键见 ErrorMessage 系列常量)。
	ErrorMessages map[string]string `toml:"error_messages"`
	// contains filtered or unexported fields
}

Config 定义 webx Server 的全部配置项,通过 confx 从 TOML 文件加载。 所有校验在 Validate() 中集中进行,失败返回 errx 结构化错误。

func LoadConfig

func LoadConfig(path string) (Config, error)

LoadConfig 通过 confx 从 TOML 文件加载配置并校验。 文件不存在、TOML 非法、存在未声明字段或校验失败时返回 errx 错误。

func (*Config) Validate

func (c *Config) Validate() error

Validate 校验配置完整性并填充默认值。 校验规则:证书/私钥必填且可配对、超时非负、日志级别合法。

type Context

type Context = core.Context

Context 是单个请求的上下文。

func NewContext

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

NewContext 创建请求上下文(用于在自定义路由器中嵌入 webx Handler)。

type GaugeMetrics

type GaugeMetrics interface {
	// AddGauge 按增量调整瞬时量(如 +1/-1)。
	AddGauge(name string, delta float64, labels ...string)
	// SetGauge 设置瞬时量绝对值。
	SetGauge(name string, value float64, labels ...string)
}

GaugeMetrics 是可选的瞬时量扩展接口。 注入的指标实例支持时,webx 会上报活跃请求与连接水位; 不支持则自动跳过,不影响主流程。

type GroupStat

type GroupStat struct {
	// Prefix 分组前缀。
	Prefix string
	// Requests 请求数。
	Requests uint64
	// Errors5xx 5xx 响应数。
	Errors5xx uint64
	// AvgRequestDurationMs 平均请求耗时(毫秒)。
	AvgRequestDurationMs uint64
}

GroupStat 单个路由分组的指标统计。

type HandlerFunc

type HandlerFunc = core.HandlerFunc

HandlerFunc 是 webx 的业务处理器签名,不依赖任何第三方类型。

type KeyFunc

type KeyFunc func(*Context) string

KeyFunc 定义限流维度的提取函数(默认按客户端 IP)。

type Metrics

type Metrics interface {
	// IncCounter 增加一个计数指标。
	IncCounter(name string, labels ...string)
	// ObserveDuration 记录一次耗时观测(秒)。
	ObserveDuration(name string, seconds float64, labels ...string)
}

Metrics 是最小指标接口,与 dbx/httpx/cachex/resiliencex 等 家族底座签名一致,metricsx 天然满足。 webx 本身不采集 Prometheus,只把事件转发给外部注入的实例。

type MetricsSnapshot

type MetricsSnapshot struct {
	// Requests 请求总数(需启用 MiddlewareMetrics)。
	Requests uint64
	// Errors5xx 5xx 响应数(需启用 MiddlewareMetrics)。
	Errors5xx uint64
	// Status1xx 1xx 响应数(需启用 MiddlewareMetrics)。
	Status1xx uint64
	// Status2xx 2xx 响应数(需启用 MiddlewareMetrics)。
	Status2xx uint64
	// Status3xx 3xx 响应数(需启用 MiddlewareMetrics)。
	Status3xx uint64
	// Status4xx 4xx 响应数(需启用 MiddlewareMetrics)。
	Status4xx uint64
	// Status5xx 5xx 响应数(需启用 MiddlewareMetrics)。
	Status5xx uint64
	// RateLimited 限流拒绝数(启用 EnableRateLimit 后统计)。
	RateLimited uint64
	// Panics Recovery 捕获的 panic 数(启用 MiddlewareRecovery 后统计)。
	Panics uint64
	// ConcurrencyRejected 并发限制拒绝数(启用 SetMaxConcurrentRequests 后统计)。
	ConcurrencyRejected uint64
	// AvgRequestDurationMs 平均请求耗时(毫秒,需启用 MiddlewareMetrics)。
	AvgRequestDurationMs uint64
	// HTTP1Requests HTTP/1.x 请求数(需启用 MiddlewareMetrics)。
	HTTP1Requests uint64
	// HTTP2Requests HTTP/2 请求数(需启用 MiddlewareMetrics)。
	HTTP2Requests uint64
	// HTTP3Requests HTTP/3 请求数(需启用 MiddlewareMetrics)。
	HTTP3Requests uint64
	// AvgHTTP1RequestDurationMs HTTP/1.x 平均请求耗时(毫秒,需启用 MiddlewareMetrics)。
	AvgHTTP1RequestDurationMs uint64
	// AvgHTTP2RequestDurationMs HTTP/2 平均请求耗时(毫秒,需启用 MiddlewareMetrics)。
	AvgHTTP2RequestDurationMs uint64
	// AvgHTTP3RequestDurationMs HTTP/3 平均请求耗时(毫秒,需启用 MiddlewareMetrics)。
	AvgHTTP3RequestDurationMs uint64
	// ActiveConnections 当前打开的连接数。
	ActiveConnections int64
	// RequestsInFlight 当前活跃请求数(需启用 MiddlewareMetrics)。
	RequestsInFlight int64
}

MetricsSnapshot 是 webx 运行指标快照,可接入监控面板。

type MiddlewareType

type MiddlewareType string

MiddlewareType 标识内置中间件的类型。

const (
	// MiddlewareRequestID 请求 ID 生成中间件。
	MiddlewareRequestID MiddlewareType = "request_id"
	// MiddlewareCORS 跨域处理中间件。
	MiddlewareCORS MiddlewareType = "cors"
	// MiddlewareTimeout 请求超时中间件。
	MiddlewareTimeout MiddlewareType = "timeout"
	// MiddlewareRecovery Panic 捕获中间件。
	MiddlewareRecovery MiddlewareType = "recovery"
	// MiddlewareValidation 请求参数校验中间件。
	MiddlewareValidation MiddlewareType = "validation"
	// MiddlewareRateLimit IP 令牌桶限流中间件。
	MiddlewareRateLimit MiddlewareType = "rate_limit"
	// MiddlewareGzip 响应压缩中间件。
	MiddlewareGzip MiddlewareType = "gzip"
	// MiddlewareMetrics 请求/5xx 计数中间件。
	MiddlewareMetrics MiddlewareType = "metrics"
	// MiddlewareSecurity 安全响应头中间件。
	MiddlewareSecurity MiddlewareType = "security"
	// MiddlewareAccessLog 访问日志中间件。
	MiddlewareAccessLog MiddlewareType = "access_log"
)

type RateLimitOptions

type RateLimitOptions struct {
	// QPS 每 IP 每秒允许的请求数(必填,> 0)。
	QPS int
	// Window 限流窗口时长(必填,> 0)。
	Window time.Duration
	// Whitelist 白名单 IP/CIDR 列表(可选)。
	Whitelist []string
	// CleanupInterval 过期桶清理间隔(可选,0 = 默认 5 分钟)。
	CleanupInterval time.Duration
	// KeyFunc 限流维度提取函数(可选,默认按客户端 IP)。
	KeyFunc KeyFunc
}

RateLimitOptions 定义 IP 限流中间件的配置参数。

type RequestIDOptions

type RequestIDOptions struct {
	// Header 请求 ID 头名(默认 X-Request-ID)。
	Header string
	// Generator 请求 ID 生成函数(默认 UUID v7)。
	Generator func() string
}

RequestIDOptions 定义请求 ID 中间件的配置参数。

type Route

type Route struct {
	// Method HTTP 方法,如 GET、POST、PUT、DELETE、PATCH。
	Method string
	// Path 路由路径,支持 gin 风格 "/api/users/:id" 与 "/assets/*filepath"。
	Path string
	// Handler 路由处理器。
	Handler HandlerFunc
	// Middleware 路由专属中间件(可选),仅对当前路由生效。
	Middleware []HandlerFunc
	// Group 路由所属分组前缀(由 RouteGroup 自动填充,供分组级指标聚合;直接注册的路由留空)。
	Group string
}

Route 定义一条 HTTP 路由。

type RouteGroup

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

RouteGroup 路由分组,支持嵌套分组和分组级中间件。 仅缓冲注册,Start() 时一次性挂载。

func (*RouteGroup) DELETE

func (rg *RouteGroup) DELETE(path string, handler HandlerFunc, mw ...HandlerFunc)

DELETE 注册一条 DELETE 方法路由。

func (*RouteGroup) GET

func (rg *RouteGroup) GET(path string, handler HandlerFunc, mw ...HandlerFunc)

GET 注册一条 GET 方法路由。

func (*RouteGroup) Group

func (rg *RouteGroup) Group(relativePath string) *RouteGroup

Group 创建子分组,继承父分组 prefix 与中间件。

func (*RouteGroup) HEAD

func (rg *RouteGroup) HEAD(path string, handler HandlerFunc, mw ...HandlerFunc)

HEAD 注册一条 HEAD 方法路由。

func (*RouteGroup) OPTIONS

func (rg *RouteGroup) OPTIONS(path string, handler HandlerFunc, mw ...HandlerFunc)

OPTIONS 注册一条 OPTIONS 方法路由。

func (*RouteGroup) PATCH

func (rg *RouteGroup) PATCH(path string, handler HandlerFunc, mw ...HandlerFunc)

PATCH 注册一条 PATCH 方法路由。

func (*RouteGroup) POST

func (rg *RouteGroup) POST(path string, handler HandlerFunc, mw ...HandlerFunc)

POST 注册一条 POST 方法路由。

func (*RouteGroup) PUT

func (rg *RouteGroup) PUT(path string, handler HandlerFunc, mw ...HandlerFunc)

PUT 注册一条 PUT 方法路由。

func (*RouteGroup) Use

func (rg *RouteGroup) Use(middleware ...HandlerFunc)

Use 向当前分组追加中间件,影响该分组内所有已注册和后续注册的路由。

type RouteStat

type RouteStat struct {
	// Path 路由注册路径。
	Path string
	// Requests 请求数。
	Requests uint64
	// Errors5xx 5xx 响应数。
	Errors5xx uint64
	// AvgRequestDurationMs 平均请求耗时(毫秒)。
	AvgRequestDurationMs uint64
}

RouteStat 单条路由的指标统计。

type Router

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

Router 基于自研 radix 匹配树实现路由: 支持 gin 风格语法(:id / *filepath)、404/405 标准化 JSON 与尾斜杠重定向。 匹配与分发均由自身完成,不依赖 http.ServeMux。

func NewRouter

func NewRouter(noRoute, noMethod core.HandlerFunc) *Router

NewRouter 创建路由,并指定 404/405 兜底处理器。

Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/lcylpzls/webx/v2"
)

func main() {
	rt := webx.NewRouter(webx.NoRouteHandler, webx.NoMethodHandler)
	_ = rt.Handle("GET", "/ping", []webx.HandlerFunc{
		func(c *webx.Context) { c.Success("pong", nil) },
	})
	rec := httptest.NewRecorder()
	rt.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/ping", nil))
	fmt.Println(rec.Code)
}
Output:
200

func (*Router) Handle

func (rt *Router) Handle(method, path string, chain []core.HandlerFunc) error

Handle 注册一条路由(chain 为全局中间件 + 路由中间件 + 最终处理器的完整链)。

func (*Router) HandleStatic

func (rt *Router) HandleStatic(prefix string, fs http.FileSystem) error

HandleStatic 注册静态文件服务(支持子树路径)。

func (*Router) HandleStaticWithOptions

func (rt *Router) HandleStaticWithOptions(prefix string, fs http.FileSystem, opts StaticOptions) error

HandleStaticWithOptions 注册静态文件服务(含缓存头/目录索引选项)。

func (*Router) ServeHTTP

func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP 实现 http.Handler:树匹配 + 方法判定 + 分发。

func (*Router) SetMaxBodyBytes

func (rt *Router) SetMaxBodyBytes(n int64)

SetMaxBodyBytes 设置路由处理链中 BindJSON 的最大请求体字节数。

type SNICertificate

type SNICertificate struct {
	// ServerName 客户端 SNI 主机名(如 "api.example.com")。
	ServerName string
	// CertFile 该域名证书文件。
	CertFile string
	// KeyFile 该域名私钥文件。
	KeyFile string
}

SNICertificate 是按 ServerName(SNI)指定的证书。

type Server

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

Server 是 webx 的核心类型,提供多通道 HTTPS 服务能力。 通过链式 API 配置,Start() 启动,Stop(ctx) 优雅关闭。

func NewServer

func NewServer(cfg Config, logger logx.Logger) *Server

NewServer 创建 webx Server 实例。 logger 由调用方注入(logx.Logger),webx 内部只使用、不创建日志器; logger 为 nil 时 Start() 会返回错误。

func (*Server) DisableMiddleware

func (s *Server) DisableMiddleware(mt ...MiddlewareType) *Server

DisableMiddleware 禁用指定类型的内置中间件。

func (*Server) DisableRateLimit

func (s *Server) DisableRateLimit() *Server

DisableRateLimit 禁用 IP 限流中间件。

func (*Server) EnableMiddleware

func (s *Server) EnableMiddleware(mt ...MiddlewareType) *Server

EnableMiddleware 重新启用指定类型的内置中间件(RateLimit 除外)。

func (*Server) EnableRateLimit

func (s *Server) EnableRateLimit(opts RateLimitOptions) *Server

EnableRateLimit 启用 IP 限流中间件。

func (*Server) EnableSPA

func (s *Server) EnableSPA(filesys http.FileSystem, indexPath string) *Server

EnableSPA 启用 SPA 回退:未匹配路由的 GET/HEAD 请求先尝试文件,再回退 index。

func (*Server) GroupStats

func (s *Server) GroupStats() []GroupStat

GroupStats 返回分组级统计快照(按分组前缀排序;需启用 MiddlewareMetrics)。

func (*Server) ListenerAddr

func (s *Server) ListenerAddr() string

ListenerAddr 返回第一个 Listener 的监听地址(port 0 动态端口时可用)。

func (*Server) Metrics

func (s *Server) Metrics() MetricsSnapshot

Metrics 返回运行指标快照;未启用对应能力时字段为 0。 快照来自 webx 内部轻量计数器,与外部 metricsx 转发互不干扰。

func (*Server) OverrideMiddleware

func (s *Server) OverrideMiddleware(mt MiddlewareType, mw HandlerFunc) *Server

OverrideMiddleware 使用自定义 Handler 覆盖指定类型的内置中间件。

func (*Server) RegisterHealthCheck

func (s *Server) RegisterHealthCheck(name string, fn func(context.Context) error) *Server

RegisterHealthCheck 注册自定义健康检查项,/health 会执行全部检查项。

func (*Server) RegisterLivenessCheck

func (s *Server) RegisterLivenessCheck(name string, fn func(context.Context) error) *Server

RegisterLivenessCheck 注册存活探针检查项,/healthz 会执行全部存活检查项。

func (*Server) RegisterOnShutdown

func (s *Server) RegisterOnShutdown(fn func()) *Server

RegisterOnShutdown 注册关闭钩子(http.Server.Shutdown 触发时执行)。

func (*Server) RegisterReadinessCheck

func (s *Server) RegisterReadinessCheck(name string, fn func(context.Context) error) *Server

RegisterReadinessCheck 注册就绪探针检查项,/readyz 会执行全部就绪检查项。 服务进入优雅关闭后,就绪探针直接返回 503。

func (*Server) RegisterRoute

func (s *Server) RegisterRoute(r Route) *Server

RegisterRoute 注册单条路由。

func (*Server) RegisterRouteGroup

func (s *Server) RegisterRouteGroup(prefix string, fn func(*RouteGroup)) *Server

RegisterRouteGroup 注册路由分组。

func (*Server) RegisterRoutes

func (s *Server) RegisterRoutes(routes []Route) *Server

RegisterRoutes 批量注册路由。

func (*Server) RouteStats

func (s *Server) RouteStats() []RouteStat

RouteStats 返回路由级统计快照(按注册路径排序;需启用 MiddlewareMetrics)。

func (*Server) ServeStaticDir

func (s *Server) ServeStaticDir(prefix, root string) *Server

ServeStaticDir 从本地目录提供静态文件。

func (*Server) ServeStaticDirWithOptions

func (s *Server) ServeStaticDirWithOptions(prefix, root string, opts StaticOptions) *Server

ServeStaticDirWithOptions 从本地目录提供静态文件,并应用选项。

func (*Server) ServeStaticFS

func (s *Server) ServeStaticFS(prefix string, filesys http.FileSystem) *Server

ServeStaticFS 从 http.FileSystem 提供静态文件,配合 embed 使用。

func (*Server) ServeStaticFSWithOptions

func (s *Server) ServeStaticFSWithOptions(prefix string, filesys http.FileSystem, opts StaticOptions) *Server

ServeStaticFSWithOptions 从 http.FileSystem 提供静态文件,并应用选项。

func (*Server) SetCertificateLoader

func (s *Server) SetCertificateLoader(fn func(*tls.ClientHelloInfo) (*tls.Certificate, error)) *Server

SetCertificateLoader 设置自定义证书加载器(用于 SNI 多证书、KMS 等场景)。 未设置时默认从 Config 的证书/私钥文件按需加载并缓存(文件变化自动重载)。

func (*Server) SetConnContext

func (s *Server) SetConnContext(fn func(context.Context, net.Conn) context.Context) *Server

SetConnContext 设置每连接上下文注入函数(供链路/连接级数据传播)。

func (*Server) SetErrorMessages

func (s *Server) SetErrorMessages(messages map[string]string) *Server

SetErrorMessages 覆盖内置错误响应文案(启动前调用)。 与 Config.ErrorMessages 合并,此处设置优先。

func (*Server) SetMaxConcurrentRequests

func (s *Server) SetMaxConcurrentRequests(n int) *Server

SetMaxConcurrentRequests 设置同时处理的请求数上限(启动前调用)。 n <= 0 表示不限制;超限请求返回 503 并携带 Retry-After。

func (*Server) SetMiddlewareOrder

func (s *Server) SetMiddlewareOrder(order []MiddlewareType) *Server

SetMiddlewareOrder 设置内置中间件执行顺序(默认顺序保持不变)。

func (*Server) SetRequestIDOptions

func (s *Server) SetRequestIDOptions(opts RequestIDOptions) *Server

SetRequestIDOptions 设置请求 ID 中间件的配置(启动前调用)。

func (*Server) SetSNICertificates

func (s *Server) SetSNICertificates(certs []SNICertificate) *Server

SetSNICertificates 设置按 SNI 域名区分的多证书;未匹配域名回退到默认证书。

func (*Server) Start

func (s *Server) Start() error

Start 启动服务:校验配置、装配中间件、注册路由、创建各通道监听器。 调用后阻塞直到服务关闭或发生错误。

func (*Server) Stop

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

Stop 优雅关闭服务(幂等,可重复调用)。

func (*Server) UseGlobalMiddleware

func (s *Server) UseGlobalMiddleware(mw ...HandlerFunc) *Server

UseGlobalMiddleware 追加外部全局中间件。

func (*Server) UseHttp2Listen

func (s *Server) UseHttp2Listen(addr string) *Server

UseHttp2Listen 启用 HTTP/2 TLS 监听(含 HTTP/1.1 兼容)。

func (*Server) UseHttp3Listen

func (s *Server) UseHttp3Listen(addr string) *Server

UseHttp3Listen 启用 HTTP/3 QUIC 监听。

func (*Server) UseUnixSocketListen

func (s *Server) UseUnixSocketListen(path string, perm os.FileMode) *Server

UseUnixSocketListen 启用 Unix Socket 监听。 Windows 需 build 1803+,兼容性检查在 Start() 时执行。

func (*Server) WithLogger

func (s *Server) WithLogger(l logx.Logger) *Server

WithLogger 注入自定义 logx.Logger。

func (*Server) WithMetrics

func (s *Server) WithMetrics(m Metrics) *Server

WithMetrics 注入外部指标接收器(metricsx 或其他实现),启动前调用。 接收器实现 GaugeMetrics 时自动上报活跃请求/连接水位; 传 nil 表示关闭外部转发,仅保留内部快照统计。

type StandardizedResponse

type StandardizedResponse = core.StandardizedResponse

StandardizedResponse 是统一的标准 JSON 响应体。

type StaticOptions

type StaticOptions struct {
	// MaxAge 设置 Cache-Control: max-age(0 表示不设置)。
	MaxAge time.Duration
	// DisableIndex 禁用目录索引:无 index.html 的目录返回 404。
	DisableIndex bool
	// EnableETag 按文件 mtime 与大小生成弱 ETag,支持 If-None-Match 返回 304。
	EnableETag bool
}

StaticOptions 定义静态文件服务的选项。

Directories

Path Synopsis
internal
core
Package core 提供 webx 的请求上下文、中间件链与标准化响应等核心原语。
Package core 提供 webx 的请求上下文、中间件链与标准化响应等核心原语。
Package middleware 提供 webx 内置的 HTTP 中间件实现。
Package middleware 提供 webx 内置的 HTTP 中间件实现。
Package pprof 注册标准库 net/http/pprof 处理器,便于线上性能诊断。
Package pprof 注册标准库 net/http/pprof 处理器,便于线上性能诊断。
Package proxy 提供基于标准库 httputil.ReverseProxy 的上游代理封装。
Package proxy 提供基于标准库 httputil.ReverseProxy 的上游代理封装。

Jump to

Keyboard shortcuts

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