Documentation
¶
Overview ¶
Package webx 提供基于 Go 标准库的工业级 HTTP/HTTPS 服务组件库。 路由基于自研 radix 匹配树,上下文与中间件链自研,日志/错误/配置 分别接入 logx / errx / confx,HTTP/3 使用 quic-go。
Index ¶
- Constants
- Variables
- func GracefulShutdown(ctx context.Context, logger logx.Logger, httpServer *http.Server, ...) error
- func RespondError(c *Context, err error)
- func RespondErrorWithData(c *Context, err error, data any)
- func StatusForError(err error) int
- type Config
- type Context
- type GaugeMetrics
- type GroupStat
- type HandlerFunc
- type KeyFunc
- type Metrics
- type MetricsSnapshot
- type MiddlewareType
- type RateLimitOptions
- type RequestIDOptions
- type Route
- type RouteGroup
- func (rg *RouteGroup) DELETE(path string, handler HandlerFunc, mw ...HandlerFunc)
- func (rg *RouteGroup) GET(path string, handler HandlerFunc, mw ...HandlerFunc)
- func (rg *RouteGroup) Group(relativePath string) *RouteGroup
- func (rg *RouteGroup) HEAD(path string, handler HandlerFunc, mw ...HandlerFunc)
- func (rg *RouteGroup) OPTIONS(path string, handler HandlerFunc, mw ...HandlerFunc)
- func (rg *RouteGroup) PATCH(path string, handler HandlerFunc, mw ...HandlerFunc)
- func (rg *RouteGroup) POST(path string, handler HandlerFunc, mw ...HandlerFunc)
- func (rg *RouteGroup) PUT(path string, handler HandlerFunc, mw ...HandlerFunc)
- func (rg *RouteGroup) Use(middleware ...HandlerFunc)
- type RouteStat
- type Router
- func (rt *Router) Handle(method, path string, chain []core.HandlerFunc) error
- func (rt *Router) HandleStatic(prefix string, fs http.FileSystem) error
- func (rt *Router) HandleStaticWithOptions(prefix string, fs http.FileSystem, opts StaticOptions) error
- func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (rt *Router) SetMaxBodyBytes(n int64)
- type SNICertificate
- type Server
- func (s *Server) DisableMiddleware(mt ...MiddlewareType) *Server
- func (s *Server) DisableRateLimit() *Server
- func (s *Server) EnableMiddleware(mt ...MiddlewareType) *Server
- func (s *Server) EnableRateLimit(opts RateLimitOptions) *Server
- func (s *Server) EnableSPA(filesys http.FileSystem, indexPath string) *Server
- func (s *Server) GroupStats() []GroupStat
- func (s *Server) ListenerAddr() string
- func (s *Server) Metrics() MetricsSnapshot
- func (s *Server) OverrideMiddleware(mt MiddlewareType, mw HandlerFunc) *Server
- func (s *Server) RegisterHealthCheck(name string, fn func(context.Context) error) *Server
- func (s *Server) RegisterLivenessCheck(name string, fn func(context.Context) error) *Server
- func (s *Server) RegisterOnShutdown(fn func()) *Server
- func (s *Server) RegisterReadinessCheck(name string, fn func(context.Context) error) *Server
- func (s *Server) RegisterRoute(r Route) *Server
- func (s *Server) RegisterRouteGroup(prefix string, fn func(*RouteGroup)) *Server
- func (s *Server) RegisterRoutes(routes []Route) *Server
- func (s *Server) RouteStats() []RouteStat
- func (s *Server) ServeStaticDir(prefix, root string) *Server
- func (s *Server) ServeStaticDirWithOptions(prefix, root string, opts StaticOptions) *Server
- func (s *Server) ServeStaticFS(prefix string, filesys http.FileSystem) *Server
- func (s *Server) ServeStaticFSWithOptions(prefix string, filesys http.FileSystem, opts StaticOptions) *Server
- func (s *Server) SetCertificateLoader(fn func(*tls.ClientHelloInfo) (*tls.Certificate, error)) *Server
- func (s *Server) SetConnContext(fn func(context.Context, net.Conn) context.Context) *Server
- func (s *Server) SetErrorMessages(messages map[string]string) *Server
- func (s *Server) SetMaxConcurrentRequests(n int) *Server
- func (s *Server) SetMiddlewareOrder(order []MiddlewareType) *Server
- func (s *Server) SetRequestIDOptions(opts RequestIDOptions) *Server
- func (s *Server) SetSNICertificates(certs []SNICertificate) *Server
- func (s *Server) Start() error
- func (s *Server) Stop(ctx context.Context) error
- func (s *Server) UseGlobalMiddleware(mw ...HandlerFunc) *Server
- func (s *Server) UseHttp2Listen(addr string) *Server
- func (s *Server) UseHttp3Listen(addr string) *Server
- func (s *Server) UseUnixSocketListen(path string, perm os.FileMode) *Server
- func (s *Server) WithLogger(l logx.Logger) *Server
- func (s *Server) WithMetrics(m Metrics) *Server
- type StandardizedResponse
- type StaticOptions
Examples ¶
Constants ¶
const ( CodeSuccess = core.CodeSuccess CodeBadRequest = core.CodeBadRequest CodeNotFound = core.CodeNotFound CodeMethodNotAllowed = core.CodeMethodNotAllowed CodeTooManyRequests = core.CodeTooManyRequests CodeInternalError = core.CodeInternalError )
标准化响应业务码。
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 覆盖)。
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 ¶
var NoMethodHandler = core.NoMethodHandler
NoMethodHandler 405 兜底处理器。
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 ¶
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 ¶
RespondErrorWithData 将 errx 错误映射为标准化错误响应,并附带业务数据。
func StatusForError ¶
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 ¶
LoadConfig 通过 confx 从 TOML 文件加载配置并校验。 文件不存在、TOML 非法、存在未声明字段或校验失败时返回 errx 错误。
type 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 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 ¶
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 ¶
NewServer 创建 webx Server 实例。 logger 由调用方注入(logx.Logger),webx 内部只使用、不创建日志器; logger 为 nil 时 Start() 会返回错误。
func (*Server) DisableMiddleware ¶
func (s *Server) DisableMiddleware(mt ...MiddlewareType) *Server
DisableMiddleware 禁用指定类型的内置中间件。
func (*Server) DisableRateLimit ¶
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 ¶
GroupStats 返回分组级统计快照(按分组前缀排序;需启用 MiddlewareMetrics)。
func (*Server) ListenerAddr ¶
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 ¶
RegisterHealthCheck 注册自定义健康检查项,/health 会执行全部检查项。
func (*Server) RegisterLivenessCheck ¶
RegisterLivenessCheck 注册存活探针检查项,/healthz 会执行全部存活检查项。
func (*Server) RegisterOnShutdown ¶
RegisterOnShutdown 注册关闭钩子(http.Server.Shutdown 触发时执行)。
func (*Server) RegisterReadinessCheck ¶
RegisterReadinessCheck 注册就绪探针检查项,/readyz 会执行全部就绪检查项。 服务进入优雅关闭后,就绪探针直接返回 503。
func (*Server) RegisterRoute ¶
RegisterRoute 注册单条路由。
func (*Server) RegisterRouteGroup ¶
func (s *Server) RegisterRouteGroup(prefix string, fn func(*RouteGroup)) *Server
RegisterRouteGroup 注册路由分组。
func (*Server) RegisterRoutes ¶
RegisterRoutes 批量注册路由。
func (*Server) RouteStats ¶
RouteStats 返回路由级统计快照(按注册路径排序;需启用 MiddlewareMetrics)。
func (*Server) ServeStaticDir ¶
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 ¶
SetConnContext 设置每连接上下文注入函数(供链路/连接级数据传播)。
func (*Server) SetErrorMessages ¶
SetErrorMessages 覆盖内置错误响应文案(启动前调用)。 与 Config.ErrorMessages 合并,此处设置优先。
func (*Server) SetMaxConcurrentRequests ¶
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) UseGlobalMiddleware ¶
func (s *Server) UseGlobalMiddleware(mw ...HandlerFunc) *Server
UseGlobalMiddleware 追加外部全局中间件。
func (*Server) UseHttp2Listen ¶
UseHttp2Listen 启用 HTTP/2 TLS 监听(含 HTTP/1.1 兼容)。
func (*Server) UseHttp3Listen ¶
UseHttp3Listen 启用 HTTP/3 QUIC 监听。
func (*Server) UseUnixSocketListen ¶
UseUnixSocketListen 启用 Unix Socket 监听。 Windows 需 build 1803+,兼容性检查在 Start() 时执行。
func (*Server) WithLogger ¶
WithLogger 注入自定义 logx.Logger。
func (*Server) WithMetrics ¶
WithMetrics 注入外部指标接收器(metricsx 或其他实现),启动前调用。 接收器实现 GaugeMetrics 时自动上报活跃请求/连接水位; 传 nil 表示关闭外部转发,仅保留内部快照统计。
type StandardizedResponse ¶
type StandardizedResponse = core.StandardizedResponse
StandardizedResponse 是统一的标准 JSON 响应体。
Source Files
¶
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 的上游代理封装。 |