httpserver

package
v0.9.6 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: MIT Imports: 27 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package httpserver 提供根 HTTP 中间件链,标准库风格:接缝只出现 http.Handler,与 appkit.Middleware(httpserver.Base(log)...) 组合使用。 模块内部选用什么 web 框架是模块自己的事,本包不出现 gin 类型。

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AccessLog

func AccessLog(log *slog.Logger) func(http.Handler) http.Handler

AccessLog 每请求记录一条访问日志:method/path/status/bytes/duration/request_id。 探针路径(/healthz、/readyz)不记录。日志在 defer 里落,panic 上抛的请求 也会留下记录(此时状态按 500 记——外层 Recover 会写 500)。

func Base

func Base(log *slog.Logger) []func(http.Handler) http.Handler

Base 返回推荐的根中间件链,外层在前(与 appkit.Middleware 的约定一致): RequestID → Recover → AccessLog → OTel。

func ClientIP

func ClientIP(trusted ...netip.Prefix) func(http.Handler) http.Handler

ClientIP 在链上解析一次真实客户端 IP 存进 ctx(callctx.ClientIP 读取), 之后模块任意深度可取、不可重算——信任决策只发生在这里。

trusted 是可信代理网段(如负载均衡、内部服务网段):

  • 对端不在可信网段:直接用 TCP 对端地址,请求头一律不信—— 转发头是调用方可以随便写的,信了等于把限流、风控、审计的 IP 全部交给伪造方;
  • 对端在可信网段:依次信 X-Client-IP(可信代理或内部跳写入的 原始客户端 IP)、X-Forwarded-For 从右往左第一个不可信地址 (可信代理逐跳追加,最右是最近的跳;伪造的注入永远在最左, 走不到答案);全链可信时取最左(起点本身是可信代理)。

零个可信网段 = 永远用 TCP 对端地址,是安全默认:直连部署直接可用, 前面有代理时组合根把网段配上(配置解析与校验留在组合根,启动期失败)。

建议放在 Base 链之后挂(appkit.Middleware 里追加),任何需要 IP 的 中间件与 handler 之前。

func DialSecureWebSocket added in v0.9.6

func DialSecureWebSocket[Send, Receive any](
	ctx context.Context,
	address string,
	cfg WebSocketConfig,
	secure contract.SecureClientOptions,
) (contract.ClientStream[Send, Receive], error)

DialSecureWebSocket 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.

func NewSSEHandler added in v0.9.6

func NewSSEHandler[Request, Event any](
	cfg SSEConfig,
	handler SSEHandler[Request, Event],
) (http.Handler, error)

NewSSEHandler 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.

Example
package main

import (
	"context"
	"time"

	"github.com/forgeplex/appkit"
	"github.com/forgeplex/appkit/contract"
	"github.com/forgeplex/appkit/httpserver"
)

func main() {
	type Request struct{ Prompt string }
	type Event struct{ Text string }

	streamHandler, err := httpserver.NewSSEHandler[Request, Event](
		httpserver.SSEConfig{
			System: "assistant",
			Method: "Generate",
			Stream: contract.StreamConfig{
				MaxDuration:  2 * time.Minute,
				IdleTimeout:  30 * time.Second,
				CloseTimeout: 3 * time.Second,
				QueueSize:    16,
			},
			MaxRequestBodyBytes: 1 << 20,
			WriteTimeout:        10 * time.Second,
			HeartbeatInterval:   15 * time.Second,
		},
		func(ctx context.Context, _ string, peer contract.Stream[httpserver.SSEEvent[Event], Request]) error {
			request, err := peer.Recv(ctx)
			if err != nil {
				return err
			}
			return peer.Send(ctx, httpserver.SSEEvent[Event]{
				ID:   "application-cursor-1",
				Data: Event{Text: request.Prompt},
			})
		},
	)
	if err != nil {
		panic(err)
	}

	module := appkit.ModuleFunc("assistant", func(reg *appkit.Registry) error {
		reg.MountAuthenticated("/events", streamHandler)
		return nil
	})
	// The app explicitly selects a security profile. Its normal Run/Start owner
	// controls the listener lifecycle; the SSE route stays behind that root.
	_ = appkit.New([]appkit.Module{module}, appkit.Security(appkit.SecurityUserFacing))
}

func NewWebSocketHandler added in v0.9.6

func NewWebSocketHandler[Send, Receive any](
	cfg WebSocketConfig,
	identity WebSocketIdentityResolver,
	handler WebSocketHandler[Send, Receive],
) (http.Handler, error)

NewWebSocketHandler 创建 JSON text-frame Bidi handler。调用方必须先把结果 挂到 Registry 的 MountAuthenticated、MountPermission 或 MountInternalService 路由;该 handler 还会独立要求可信 Actor/ServicePrincipal。

func OTel

func OTel() func(http.Handler) http.Handler

OTel 用 otelhttp 包装下游,span 名为 "METHOD pattern"。探针路径不产生 span(与 AccessLog 同一套 isProbe 判断)。 formatter 会被调用两次:span 起始时 ServeMux 尚未匹配(r.Pattern 为空, 先以 method 起名),handler 返回后 otelhttp 用它按 pattern 重命名。 带方法的 pattern(含空格)不再重复拼 method。

func Recover

func Recover(log *slog.Logger) func(http.Handler) http.Handler

Recover 捕获下游 panic:记录 error 级日志(含堆栈),并以 problem+json 写出 500。http.ErrAbortHandler 是 net/http 认可的中止方式,原样上抛。 若响应头已发出,这里的 WriteHeader 无效但无害(net/http 忽略并告警)。

func RequestID

func RequestID() func(http.Handler) http.Handler

RequestID 从请求头提取跨边界元数据白名单并存进 ctx,request id 缺省时 生成 uuid 并回写响应头。严格安全模式的 identity boundary 位于本链之外, 已先清除 unsigned 租户/caller 头,因此这里只会读到可追踪但不授权的 request id;SecurityDisabled 保留历史的原样提取行为。 放在链最外层,保证 Recover/AccessLog 的日志都带 request id。

func RequestIDFrom

func RequestIDFrom(ctx context.Context) string

RequestIDFrom 取出当前请求的 request id;不存在时返回空串。 需要租户等其它字段时用 callctx.From(ctx)。

func WriteError

func WriteError(log *slog.Logger, w http.ResponseWriter, err error)

WriteError 是服务端错误响应的统一出口:规范化为 apperr 后写 RFC 9457 响应;5xx 时记录一条 error 日志(含完整错误链)。整条请求路径只应在 这里 log 一次错误——上游层 wrap 后原样上抛即可,不要边 log 边返回。

Types

type SSEConfig added in v0.9.6

type SSEConfig struct {
	// System and Method are stable contract names used by the Local Stream span.
	System string
	Method string
	// Stream defines max lifetime, idle policy, close budget, and bounded queue.
	Stream contract.StreamConfig
	// MaxRequestBodyBytes is the maximum JSON request size and must be positive.
	MaxRequestBodyBytes int64
	// WriteTimeout bounds each individual data, heartbeat, or error frame write.
	// It does not alter http.Server.WriteTimeout for other routes.
	WriteTimeout time.Duration
	// HeartbeatInterval emits comment frames to keep intermediaries from timing
	// out an otherwise active response. Zero disables heartbeats.
	HeartbeatInterval time.Duration
}

SSEConfig 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.

type SSEEvent added in v0.9.6

type SSEEvent[T any] struct {
	ID   string
	Data T
}

SSEEvent 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.

type SSEHandler added in v0.9.6

type SSEHandler[Request, Event any] func(
	context.Context,
	string,
	contract.Stream[SSEEvent[Event], Request],
) error

SSEHandler 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.

type WebSocketConfig added in v0.9.6

type WebSocketConfig struct {
	System string
	Method string
	Stream contract.StreamConfig
	// MaxMessageBytes 限制一条 JSON 消息 payload,不含内部 wire envelope。
	MaxMessageBytes int64
	// HandshakeTimeout 限制升级响应写入时间。
	HandshakeTimeout time.Duration
	// WriteTimeout 限制每个 WebSocket frame 的写入时间。
	WriteTimeout time.Duration
	// OriginPatterns 仅用于放行跨 Origin 浏览器请求;匹配请求 scheme 与 host
	// 的同源请求始终允许,缺省拒绝所有跨源请求。禁止使用 "*"。
	OriginPatterns []string
	// Hub 跟踪 hijacked 连接,必须非 nil。
	Hub *WebSocketHub
	// IdentityResolver 可由生成的 Handler 使用,以适配自定义认证器;为空时
	// 生成绑定从 AppKit Actor/ServicePrincipal 读取认证身份。
	IdentityResolver WebSocketIdentityResolver
}

WebSocketConfig 为一条 V2 Bidi Stream 定义传输预算。Stream.QueueSize 限制每个方向的排队帧数;MaxMessageBytes 限制每帧 JSON payload,因而队列 同时具有帧数与字节上限。Hub 必须注册为 Host ManagedService,保证连接可 被关停流程追踪。

type WebSocketHandler added in v0.9.6

type WebSocketHandler[Send, Receive any] func(context.Context, contract.Stream[Receive, Send]) error

WebSocketHandler 处理一条 Bidi Stream。与本地 contract.Stream 的服务端 视角一致:Send/Receive 类型顺序反转。

type WebSocketHub added in v0.9.6

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

WebSocketHub 是可直接作为 appkit.ManagedService 返回的连接注册表(依靠 Go 接口的结构化实现)。在模块 Register 中通过 Registry.ManagedService 注册。 Start 打开连接入口,Drain 停止新升级并按预算发送 GoingAway/强制关停。

func NewWebSocketHub added in v0.9.6

func NewWebSocketHub() *WebSocketHub

NewWebSocketHub 创建尚未 Start 的 WebSocket 连接注册表。

func (*WebSocketHub) Close added in v0.9.6

func (h *WebSocketHub) Close(ctx context.Context) error

Close 强制关闭剩余连接并等待 HTTP handler 清理完毕。

func (*WebSocketHub) Drain added in v0.9.6

func (h *WebSocketHub) Drain(ctx context.Context) error

Drain 停止接收新升级,向已建立连接发送 GoingAway,并等待在途连接退出。 超出 Host 预算时直接关闭底层 net.Conn,包括已经 Hijack 的连接。

func (*WebSocketHub) Ready added in v0.9.6

func (h *WebSocketHub) Ready(ctx context.Context) error

Ready 报告 Hub 是否已启动且仍接受连接。

func (*WebSocketHub) Run added in v0.9.6

func (h *WebSocketHub) Run(ctx context.Context) error

Run 等待 Host 取消 ManagedService Context;Drain 由 Host 在取消前调用。

func (*WebSocketHub) Start added in v0.9.6

func (h *WebSocketHub) Start(ctx context.Context) error

Start 打开升级入口;Host 在此之前启动 HTTP Listener,因此未就绪连接会被 fail-closed 拒绝。

type WebSocketIdentity added in v0.9.6

type WebSocketIdentity struct {
	Subject   string
	ExpiresAt time.Time
}

WebSocketIdentity 是 Upgrade 前由可信认证器解析出的连接身份信息。零值 ExpiresAt 表示认证器没有提供凭证过期时间。

type WebSocketIdentityResolver added in v0.9.6

type WebSocketIdentityResolver func(context.Context) (WebSocketIdentity, error)

WebSocketIdentityResolver 只能从已认证的请求 Context 构造身份;不得读取 URL、query string 或 WebSocket frame 中的身份声明。

Jump to

Keyboard shortcuts

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