{"modulePath":"github.com/forgeplex/appkit","version":"v0.10.0","isLatest":false,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package httpserver\n\nPackage httpserver 提供根 HTTP 中间件链，标准库风格：接缝只出现 http.Handler，与 appkit.Middleware(httpserver.Base(log)...) 组合使用。 模块内部选用什么 web 框架是模块自己的事，本包不出现 gin 类型。\n\n## Functions\n\n```go\nfunc AccessLog(log *slog.Logger) func(http.Handler) http.Handler\n```\nAccessLog 每请求记录一条访问日志：method/path/status/bytes/duration/request\\_id。 探针路径（/healthz、/readyz）不记录。日志在 defer 里落，panic 上抛的请求 也会留下记录（此时状态按 500 记——外层 Recover 会写 500）。\n\n```go\nfunc Base(log *slog.Logger) []func(http.Handler) http.Handler\n```\nBase 返回推荐的根中间件链，外层在前（与 appkit.Middleware 的约定一致）： RequestID → Recover → AccessLog → OTel。\n\n```go\nfunc ClientIP(trusted ...netip.Prefix) func(http.Handler) http.Handler\n```\nClientIP 在链上解析一次真实客户端 IP 存进 ctx（callctx.ClientIP 读取）， 之后模块任意深度可取、不可重算——信任决策只发生在这里。\n\ntrusted 是可信代理网段（如负载均衡、内部服务网段）：\n\n  - 对端不在可信网段：直接用 TCP 对端地址，请求头一律不信—— 转发头是调用方可以随便写的，信了等于把限流、风控、审计的 IP 全部交给伪造方；\n  - 对端在可信网段：依次信 X-Client-IP（可信代理或内部跳写入的 原始客户端 IP）、X-Forwarded-For 从右往左第一个不可信地址 （可信代理逐跳追加，最右是最近的跳；伪造的注入永远在最左， 走不到答案）；全链可信时取最左（起点本身是可信代理）。\n\n零个可信网段 = 永远用 TCP 对端地址，是安全默认：直连部署直接可用， 前面有代理时组合根把网段配上（配置解析与校验留在组合根，启动期失败）。\n\n建议放在 Base 链之后挂（appkit.Middleware 里追加），任何需要 IP 的 中间件与 handler 之前。\n\n```go\nfunc DialSecureSSE[Request, Event any](\n\tctx context.Context,\n\taddress string,\n\tcfg SSEClientConfig,\n\tsecure contract.SecureClientOptions,\n\trequest Request,\n) (contract.ServerStream[SSEEvent[Event]], error)\n```\nDialSecureSSE sends one JSON request and establishes an HTTPS-only, origin-bound server stream. Credential delegation, TLS verification and the context firewall are shared with NewSecureHTTPClient. The credential is acquired once and its signed expiry ends the stream; it is never refreshed. HTTP problems before commitment are returned by Dial; in-band error events become Recv errors with their stable code but no remote message or details.\n\nA complete event boundary followed by HTTP EOF is normal completion. The existing SSE wire protocol has no terminal marker, so a clean early EOF cannot be distinguished from intentional completion. Incomplete data events, unterminated lines and transport failures are errors. Business completion belongs in the event DTO. Streaming APIs remain experimental until explicitly promoted under ADR-0047.\n\n```go\nfunc DialSecureWebSocket[Send, Receive any](\n\tctx context.Context,\n\taddress string,\n\tcfg WebSocketConfig,\n\tsecure contract.SecureClientOptions,\n) (contract.ClientStream[Send, Receive], error)\n```\nDialSecureWebSocket opens a WSS-only, origin-bound service connection. The provider is called once for the handshake; the credential is never refreshed or resent after Upgrade. ClientStream contexts remain operation-scoped because only the stream root context is used for WebSocket IO.\n\n```go\nfunc NewSSEHandler[Request, Event any](\n\tcfg SSEConfig,\n\thandler SSEHandler[Request, Event],\n) (http.Handler, error)\n```\nNewSSEHandler creates an HTTP handler for a single POST request whose response is an SSE stream. Mount the returned handler through a classified Registry method such as MountAuthenticated or MountPermission when strict security is enabled. Use a path-only route pattern (for example, \"/events\") if method errors should use problem+json; a method-qualified ServeMux pattern may reject the request before this handler runs. This handler does not implement browser-native EventSource or replay. Streaming APIs remain experimental until explicitly promoted under ADR-0047.\n\n```go\nfunc NewWebSocketHandler[Send, Receive any](\n\tcfg WebSocketConfig,\n\tidentity WebSocketIdentityResolver,\n\thandler WebSocketHandler[Send, Receive],\n) (http.Handler, error)\n```\nNewWebSocketHandler 创建 JSON text-frame Bidi handler。调用方必须先把结果 挂到 Registry 的 MountAuthenticated、MountPermission 或 MountInternalService 路由；该 handler 还会独立要求可信 Actor/ServicePrincipal。\n\n```go\nfunc OTel() func(http.Handler) http.Handler\n```\nOTel 用 otelhttp 包装下游，span 名为 \"METHOD pattern\"。探针路径不产生 span（与 AccessLog 同一套 isProbe 判断）。 formatter 会被调用两次：span 起始时 ServeMux 尚未匹配（r.Pattern 为空， 先以 method 起名），handler 返回后 otelhttp 用它按 pattern 重命名。 带方法的 pattern（含空格）不再重复拼 method。\n\n```go\nfunc Recover(log *slog.Logger) func(http.Handler) http.Handler\n```\nRecover 捕获下游 panic：记录 error 级日志（含堆栈），并以 problem+json 写出 500。http.ErrAbortHandler 是 net/http 认可的中止方式，原样上抛。 若响应头已发出，这里的 WriteHeader 无效但无害（net/http 忽略并告警）。\n\n```go\nfunc RequestID() func(http.Handler) http.Handler\n```\nRequestID 从请求头提取跨边界元数据白名单并存进 ctx，request id 缺省时 生成 uuid 并回写响应头。严格安全模式的 identity boundary 位于本链之外， 已先清除 unsigned 租户/caller 头，因此这里只会读到可追踪但不授权的 request id；SecurityDisabled 保留历史的原样提取行为。 放在链最外层，保证 Recover/AccessLog 的日志都带 request id。\n\n```go\nfunc RequestIDFrom(ctx context.Context) string\n```\nRequestIDFrom 取出当前请求的 request id；不存在时返回空串。 需要租户等其它字段时用 callctx.From(ctx)。\n\n```go\nfunc WriteError(log *slog.Logger, w http.ResponseWriter, err error)\n```\nWriteError 是服务端错误响应的统一出口：规范化为 apperr 后写 RFC 9457 响应；5xx 时记录一条 error 日志（含完整错误链）。整条请求路径只应在 这里 log 一次错误——上游层 wrap 后原样上抛即可，不要边 log 边返回。\n\n## Types\n\n```go\ntype SSEClientConfig struct {\n\tSystem string\n\tMethod string\n\tStream contract.StreamConfig\n\t// MaxRequestBodyBytes bounds the single JSON request.\n\tMaxRequestBodyBytes int64\n\t// MaxEventBytes bounds each wire event block, including field names,\n\t// comments, cursor and delimiters, before JSON decoding. A dispatching CR\n\t// may have one additional LF framing byte, skipped without waiting for it.\n\t// QueueSize bounds decoded messages; the parser may hold one additional\n\t// event under pressure.\n\tMaxEventBytes int64\n\t// LastEventID is an optional opaque cursor sent once in Last-Event-ID.\n\t// AppKit never persists this value or retries/reconnects the stream.\n\tLastEventID string\n}\n```\nSSEClientConfig defines the budgets for one POST + SSE invocation. Stream budgets start before the HTTP handshake. A configured HTTPClient.Timeout is an additional whole-response deadline; leave it zero for a stream whose lifetime is controlled solely by Stream. Heartbeats do not reset IdleTimeout.\n\n```go\ntype SSEConfig struct {\n\t// System and Method are stable contract names used by the Local Stream span.\n\tSystem string\n\tMethod string\n\t// Stream defines max lifetime, idle policy, close budget, and bounded queue.\n\tStream contract.StreamConfig\n\t// MaxRequestBodyBytes is the maximum JSON request size and must be positive.\n\tMaxRequestBodyBytes int64\n\t// WriteTimeout bounds each individual data, heartbeat, or error frame write.\n\t// It does not alter http.Server.WriteTimeout for other routes.\n\tWriteTimeout time.Duration\n\t// HeartbeatInterval emits comment frames to keep intermediaries from timing\n\t// out an otherwise active response. Zero disables heartbeats.\n\tHeartbeatInterval time.Duration\n}\n```\nSSEConfig defines the HTTP and Local Stream budgets for one POST + SSE route. Stream durations and queue capacity are independent from the ordinary HTTP server timeouts. WriteTimeout bounds each response frame write; heartbeat is optional and, when enabled, is emitted as an SSE comment rather than an application event. Streaming APIs remain experimental until explicitly promoted under ADR-0047.\n\n```go\ntype SSEEvent[T any] struct {\n\tID   string\n\tData T\n}\n```\nSSEEvent is one application event written as a JSON SSE data frame. ID is an optional opaque application cursor, copied verbatim to the SSE id field when it contains no NUL, CR, or LF. AppKit does not parse, persist, or replay it.\n\n```go\ntype SSEHandler[Request, Event any] func(\n\tcontext.Context,\n\tstring,\n\tcontract.Stream[SSEEvent[Event], Request],\n) error\n```\nSSEHandler handles one HTTP request on the server side of a Local Stream. The opaque Last-Event-ID value is supplied unchanged. Receive one request DTO from peer, then Send zero or more SSEEvent values. Normal handler completion becomes EOF; application terminal state belongs in an event DTO.\n\n```go\ntype WebSocketConfig struct {\n\tSystem string\n\tMethod string\n\tStream contract.StreamConfig\n\t// MaxMessageBytes 限制一条 JSON 消息 payload，不含内部 wire envelope。\n\tMaxMessageBytes int64\n\t// HandshakeTimeout 限制升级响应写入时间。\n\tHandshakeTimeout time.Duration\n\t// WriteTimeout 限制每个 WebSocket frame 的写入时间。\n\tWriteTimeout time.Duration\n\t// OriginPatterns 仅用于放行跨 Origin 浏览器请求；匹配请求 scheme 与 host\n\t// 的同源请求始终允许，缺省拒绝所有跨源请求。禁止使用 \"*\"。\n\tOriginPatterns []string\n\t// Hub 跟踪 hijacked 连接，必须非 nil。\n\tHub *WebSocketHub\n\t// IdentityResolver 可由生成的 Handler 使用，以适配自定义认证器；为空时\n\t// 生成绑定从 AppKit Actor/ServicePrincipal 读取认证身份。\n\tIdentityResolver WebSocketIdentityResolver\n}\n```\nWebSocketConfig 为一条 V2 Bidi Stream 定义传输预算。Stream.QueueSize 限制每个方向的排队帧数；MaxMessageBytes 限制每帧 JSON payload，因而队列 同时具有帧数与字节上限。Hub 必须注册为 Host ManagedService，保证连接可 被关停流程追踪。\n\n```go\ntype WebSocketHandler[Send, Receive any] func(context.Context, contract.Stream[Receive, Send]) error\n```\nWebSocketHandler 处理一条 Bidi Stream。与本地 contract.Stream 的服务端 视角一致：Send/Receive 类型顺序反转。\n\n```go\ntype WebSocketHub struct {\n\t// contains filtered or unexported fields\n}\n```\nWebSocketHub 是可直接作为 appkit.ManagedService 返回的连接注册表（依靠 Go 接口的结构化实现）。在模块 Register 中通过 Registry.ManagedService 注册。 Start 打开连接入口，Drain 停止新升级并按预算发送 GoingAway/强制关停。\n\n```go\nfunc NewWebSocketHub() *WebSocketHub\n```\nNewWebSocketHub 创建尚未 Start、且未配置连接/速率预算的 WebSocket Hub。 为保持现有调用签名，该 Hub 仍可构造，但 Start 不会使其进入可接纳状态。\n\n```go\nfunc NewWebSocketHubWithLimits(limits WebSocketHubLimits) (*WebSocketHub, error)\n```\nNewWebSocketHubWithLimits 创建可接纳 WebSocket Upgrade 的 Hub。 限额必须由调用方显式提供；框架不会猜测通用容量默认值。\n\n```go\nfunc (h *WebSocketHub) Close(ctx context.Context) error\n```\nClose 强制关闭剩余连接并等待 HTTP handler 清理完毕。\n\n```go\nfunc (h *WebSocketHub) Drain(ctx context.Context) error\n```\nDrain 停止接收新升级，向已建立连接发送 GoingAway，并等待在途连接退出。 超出 Host 预算时直接关闭底层 net.Conn，包括已经 Hijack 的连接。\n\n```go\nfunc (h *WebSocketHub) Ready(ctx context.Context) error\n```\nReady 报告 Hub 是否已启动且仍接受连接。\n\n```go\nfunc (h *WebSocketHub) Run(ctx context.Context) error\n```\nRun 等待 Host 取消 ManagedService Context；Drain 由 Host 在取消前调用。\n\n```go\nfunc (h *WebSocketHub) Start(ctx context.Context) error\n```\nStart 打开升级入口；Host 在此之前启动 HTTP Listener，因此未就绪连接会被 fail-closed 拒绝。\n\n```go\ntype WebSocketHubLimits struct {\n\t// MaxConnections 限制该 Hub 中 pending reservation 与 active connection 的合计。\n\tMaxConnections int\n\t// Inbound 限制客户端发往服务端的应用 data 消息。\n\tInbound WebSocketRateLimits\n\t// Outbound 限制服务端发往客户端的应用 data 消息。\n\tOutbound WebSocketRateLimits\n}\n```\nWebSocketHubLimits 限制单个 Hub 的 pending+active 连接总数，并为每条连接 的入站和出站方向分别配置消息预算；它不是进程级或跨副本配额。\n\n```go\ntype WebSocketIdentity struct {\n\tSubject   string\n\tExpiresAt time.Time\n}\n```\nWebSocketIdentity 是 Upgrade 前由可信认证器解析出的连接身份信息。零值 ExpiresAt 表示认证器没有提供凭证过期时间。\n\n```go\ntype WebSocketIdentityResolver func(context.Context) (WebSocketIdentity, error)\n```\nWebSocketIdentityResolver 只能从已认证的请求 Context 构造身份；不得读取 URL、query string 或 WebSocket frame 中的身份声明。\n\n```go\ntype WebSocketRateLimits struct {\n\t// FramesPerSecond 是每秒允许的应用 data 帧数。\n\tFramesPerSecond int64\n\t// FrameBurst 是该方向可立即发送或接收的最大 data 帧数。\n\tFrameBurst int64\n\t// BytesPerSecond 是每秒允许的 JSON payload 字节数，不含 wire envelope。\n\tBytesPerSecond int64\n\t// ByteBurst 是该方向可立即发送或接收的最大 JSON payload 字节数。\n\tByteBurst int64\n}\n```\nWebSocketRateLimits 为 WebSocket 单方向的应用 data 消息设置速率与突发预算。\n\n","path":"github.com/forgeplex/appkit/httpserver","name":"httpserver","synopsis":"Package httpserver 提供根 HTTP 中间件链，标准库风格：接缝只出现 http.Handler，与 appkit.Middleware(httpserver.Base(log)...) 组合使用。","isRedistributable":true}
