middlewares

package
v0.0.0-...-1f1dc5f Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

README

Middlewares Package 说明

概述

Middlewares 包提供 API 模板的通用中间件能力,包括请求元数据、API Token、Login Session、CSRF、错误恢复、请求日志、压缩和可选 CORS。

中间件列表

1. 请求元数据中间件 (request_context.go)

功能: 把 request id、trace id、span id 等请求元数据写入标准 context.Context

边界约定:

  • 该中间件只搬运请求元数据,不做认证授权。
  • request id、trace id、span id 只接受长度受限的可见 ASCII 值;非法 request id 会重新生成,非法 trace/span id 会丢弃。
  • 该中间件不读取 X-User-ID 这类客户端身份 header;真实用户身份必须由认证边界验证后写入 context。
  • usecase 层通过 internal/platform/requestctx 读取元数据,不依赖 Echo context。
2. Login Session 中间件 (login_session.go)

功能: 浏览器登录会话认证和 CSRF 配置

配置:

type LoginSessionConfig struct {
    CookieName    string
    SkipPaths     []string
    Authenticator LoginSessionAuthenticator
    Enabled       bool
}

特性:

  • 支持公开路径跳过
  • login_session HttpOnly cookie 读取 opaque token
  • 通过 boot 注入的 authenticator 校验会话,不 import 业务存储
  • 验证成功后写入 requestctx.UserIDrequestctx.RoleIDrequestctx.LoginSessionID
  • API Token 已经认证的请求会跳过浏览器会话认证
  • CSRFConfig 只保护已通过 Login Session 认证的 unsafe method;API Token 请求不走浏览器 CSRF
  • 登录 handler 负责设置 login_session 和浏览器可读的 csrf_token cookie
3. 错误处理中间件 (error.go)

功能: 统一的错误处理和恢复

特性:

  • 自动 panic 恢复
  • 统一的错误响应格式
  • 错误日志记录默认只记录 URL path,不记录 query string
  • 支持业务错误码转换

边界约定:

  • internal/platform/apperr 是错误码、错误类别和对外安全消息的唯一来源,并且不依赖 HTTP。
  • ErrorHandler 是 HTTP 错误边界,负责把 Echo 错误、panic 和未知错误归一化为应用错误,并记录结构化日志。
  • internal/platform/server/httpresp.APIError 负责把 apperr.Info 映射为 HTTP 状态码和 JSON 响应。
  • Usecase 层直接返回错误,Adapter 层包装外部系统错误,业务模块只包装业务语义错误或透传已编码错误。
  • 业务错误可以返回具体、安全的 message;内部错误对外始终返回安全文案,原始错误和诊断上下文只进入日志 detail
4. 中间件配置 (config.go)

功能: 统一的中间件配置管理。请求日志使用 boot 阶段安装的 zerolog logger,并把 request id、trace id、span id、user id 等字段挂到当前请求 context。

配置:

type MiddlewareConfig struct {
    EnableRecovery       bool
    EnableRequestContext bool
    EnableLogger         bool
    EnableGzip           bool
    EnableCORS           bool
    CORS                 middleware.CORSConfig
    EnableLoginSession   bool
    LoginSession         *LoginSessionConfig
    EnableCSRF           bool
    CSRF                 middleware.CSRFConfig
}

使用示例:

config := &MiddlewareConfig{
    EnableRecovery:       true,
    EnableRequestContext: true,
    EnableLogger:         true,
    EnableGzip:           true,
    EnableCORS:           true,
    CORS: middleware.CORSConfig{
        AllowOrigins: []string{"https://app.example.com"},
    },
    EnableLoginSession: true,
    LoginSession: &LoginSessionConfig{
        CookieName:    LoginSessionCookieName,
        SkipPaths:     []string{"/api/health", "/api/info", "/api/ready"},
        Authenticator: loginSessionAuthenticator,
        Enabled:       true,
    },
    EnableCSRF: true,
    CSRF:       CSRFConfig(nil, true),
}

ApplyMiddlewares(e, config)

server.New 使用保守默认值:不启用 CORS。项目真的需要跨域时,在静态配置或环境变量里显式打开 http.cors.enabled,并确认允许的 origin,避免模板默认放大浏览器访问面。

扩展性

权限系统、租户边界、审计等业务相关中间件应由具体项目按需接入,避免 API 模板默认绑定特定授权实现。

Documentation

Overview

Package middlewares contains server-owned Echo middleware adapters.

Index

Constants

View Source
const (
	// LoginSessionCookieName is the HttpOnly browser credential for login
	// sessions.
	LoginSessionCookieName = "login_session"
	// CSRFCookieName is the browser-readable double-submit CSRF cookie.
	CSRFCookieName = "csrf_token"
)
View Source
const APIKeyHeader = "X-API-Token"

APIKeyHeader is the header used for back-office API token authentication.

Variables

This section is empty.

Functions

func APIKey

func APIKey(config *APIKeyConfig) (echo.MiddlewareFunc, error)

APIKey creates middleware that authenticates requests carrying an API token.

func ApplyMiddlewares

func ApplyMiddlewares(e *echo.Echo, config *MiddlewareConfig) error

ApplyMiddlewares installs server-owned middleware.

func CSRFConfig

func CSRFConfig(skipPaths []string, secureCookies bool) middleware.CSRFConfig

CSRFConfig returns the Echo CSRF middleware configuration used for browser login-session requests.

func ClearCSRFCookie

func ClearCSRFCookie(c *echo.Context, secure bool)

ClearCSRFCookie removes the browser-readable CSRF token.

func ClearLoginSessionCookie

func ClearLoginSessionCookie(c *echo.Context, secure bool)

ClearLoginSessionCookie removes the browser session credential.

func ErrorHandler

func ErrorHandler(c *echo.Context, err error)

ErrorHandler renders API errors without persistent system error recording.

func ErrorHandlerWithRecorder

func ErrorHandlerWithRecorder(recorder SystemErrorRecorder) echo.HTTPErrorHandler

ErrorHandlerWithRecorder renders API errors and records internal failures.

func ErrorRecovery

func ErrorRecovery() echo.MiddlewareFunc

ErrorRecovery recovers panics at the HTTP boundary.

func FormatLoginSessionID

func FormatLoginSessionID(id int64) string

FormatLoginSessionID converts positive numeric IDs to request metadata.

func InstallationGate

func InstallationGate(config *InstallationGateConfig) (echo.MiddlewareFunc, error)

InstallationGate blocks normal administration routes until setup completes.

func LoginSession

func LoginSession(config *LoginSessionConfig) (echo.MiddlewareFunc, error)

LoginSession creates browser login-session authentication middleware.

func NewCSRFToken

func NewCSRFToken() (string, error)

NewCSRFToken creates a browser-readable CSRF token for login responses.

func RequestContext

func RequestContext() echo.MiddlewareFunc

RequestContext stores request-scoped metadata in the standard context.

func SetCSRFCookie

func SetCSRFCookie(c *echo.Context, token string, expiresAt time.Time, secure bool)

SetCSRFCookie stores the browser-readable CSRF token used by Echo's CSRF middleware.

func SetLoginSessionCookie

func SetLoginSessionCookie(c *echo.Context, token string, expiresAt time.Time, secure bool)

SetLoginSessionCookie stores the opaque browser session credential.

Types

type APIKeyConfig

type APIKeyConfig struct {
	Header   string
	Verifier APIKeyVerifier
	Enabled  bool
}

APIKeyConfig controls API token authentication middleware.

func DefaultAPIKeyConfig

func DefaultAPIKeyConfig() *APIKeyConfig

DefaultAPIKeyConfig returns disabled API token authentication defaults.

type APIKeyIdentity

type APIKeyIdentity struct {
	UserID string
	RoleID string
}

APIKeyIdentity is the request identity produced by a verified API token.

type APIKeyVerifier

type APIKeyVerifier interface {
	VerifyAPIKey(context.Context, string) (APIKeyIdentity, error)
}

APIKeyVerifier validates a raw API token without exposing token storage to the server.

type InstallationGateConfig

type InstallationGateConfig struct {
	Reader    InstallationStateReader
	SkipPaths []string
	Enabled   bool
}

InstallationGateConfig controls the uninitialized-system route gate.

func DefaultInstallationGateConfig

func DefaultInstallationGateConfig() *InstallationGateConfig

DefaultInstallationGateConfig returns the public setup and system routes that remain reachable before first initialization completes.

type InstallationStateReader

type InstallationStateReader interface {
	Initialized(context.Context) (bool, error)
}

InstallationStateReader reports whether first initialization has completed.

type LoginSessionAuthenticator

type LoginSessionAuthenticator interface {
	AuthenticateLoginSession(context.Context, string) (LoginSessionIdentity, error)
}

LoginSessionAuthenticator validates browser login session credentials.

type LoginSessionConfig

type LoginSessionConfig struct {
	CookieName    string
	SkipPaths     []string
	Authenticator LoginSessionAuthenticator
	Enabled       bool
}

LoginSessionConfig controls browser login-session authentication.

func DefaultLoginSessionConfig

func DefaultLoginSessionConfig() *LoginSessionConfig

DefaultLoginSessionConfig returns disabled login-session authentication defaults.

type LoginSessionIdentity

type LoginSessionIdentity struct {
	SessionID string
	UserID    string
	RoleID    string
}

LoginSessionIdentity is the request identity produced by a verified browser login session.

type MiddlewareConfig

type MiddlewareConfig struct {
	EnableRecovery bool

	EnableRequestContext bool

	EnableLogger bool

	EnableTracing bool

	TracingServiceName string

	EnableGzip bool

	EnableCORS bool

	CORS middleware.CORSConfig

	EnableAPIKey bool

	APIKey *APIKeyConfig

	EnableInstallationGate bool

	InstallationGate *InstallationGateConfig

	EnableLoginSession bool

	LoginSession *LoginSessionConfig

	EnableCSRF bool

	CSRF middleware.CSRFConfig
}

MiddlewareConfig controls server-owned HTTP middleware.

func DefaultMiddlewareConfig

func DefaultMiddlewareConfig() *MiddlewareConfig

DefaultMiddlewareConfig returns the HTTP middleware defaults.

type SystemErrorInput

type SystemErrorInput struct {
	Code      int
	Message   string
	Detail    string
	Method    string
	Path      string
	IP        string
	UserAgent string
	RequestID string
	UserID    string
}

SystemErrorInput carries one internal API failure to a persistence adapter.

type SystemErrorRecorder

type SystemErrorRecorder interface {
	RecordSystemError(context.Context, SystemErrorInput) error
}

SystemErrorRecorder stores internal API failure diagnostics outside the server.

type Validator

type Validator struct {
	Validator *validator.Validate
}

Validator adapts go-playground validator to Echo's validation interface.

func (*Validator) Validate

func (cv *Validator) Validate(i interface{}) error

Validate checks the request DTO and returns a stable public error while keeping validator details in the wrapped cause for logs.

Jump to

Keyboard shortcuts

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