Help us shape the future of Go! Take the 2026 Go Developer Survey

server

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2026 License: AGPL-3.0 Imports: 15 Imported by: 0

Documentation

Overview

Package server 组装 HTTP 路由与服务生命周期。

Index

Constants

View Source
const (
	PrefixConsole   = api.PrefixConsole
	PrefixPublic    = api.PrefixPublic
	PrefixExtension = api.PrefixExtension
)

三平面路由前缀,定义在 api 包,这里保留别名便于引用与测试。

View Source
const UploadsPath = "/uploads"

UploadsPath 是本地存储附件的对外访问前缀。

Variables

This section is empty.

Functions

func NewRouter

func NewRouter(opts *Options) (root chi.Router, planes *api.Planes)

NewRouter 构造根路由并返回供模块注册用的三平面注册面。

三平面的鉴权策略由 api.NewPlanes 落实:

  • Console:解析凭据 + CSRF + **强制已认证**;细粒度权限由各操作声明
  • Public:解析凭据但不强制,匿名可读已发布内容
  • Extension:解析凭据 + CSRF + 强制已认证

注意:未注册的路径由根路由的 NotFound 处理并返回 404,不会先经过各平面的 鉴权中间件——这是正确行为,但排查时容易误以为鉴权没生效。

Types

type Authenticator

type Authenticator interface {
	// Middleware 解析凭据并注入 context,但不强制要求已认证。
	Middleware(next http.Handler) http.Handler
	// CSRF 校验非安全方法的 CSRF 令牌。
	CSRF(next http.Handler) http.Handler
}

Authenticator 是路由层所需的鉴权能力。

定义在使用方(消费者侧接口,Go 惯例),使 server 不依赖 auth 的具体实现, 也让接线测试可以替换成轻量替身而不必连数据库。

type Options

type Options struct {
	Logger *slog.Logger
	// Authenticator 为 nil 时不挂载鉴权中间件,仅用于测试路由骨架。
	Authenticator Authenticator
	// ClientIP 为 nil 时不解析转发头,一律使用直连地址。
	ClientIP *httpx.ClientIPResolver
	// Version 写入 OpenAPI 文档的 info.version。
	Version string
	// MaxBodySize 是普通请求体的字节上限,0 表示用默认值。
	MaxBodySize int64
	// MaxUploadSize 是 multipart 请求体的字节上限,0 表示用默认值。
	MaxUploadSize int64
	// UploadsDir 非空时把该目录以静态文件形式挂在 /uploads 下,供本地存储的附件访问。
	UploadsDir string
	// FallbackRootToConsole 为真时把根路径重定向到 Console。
	//
	// 仅供没有装配主题模块的场景(路由骨架测试、未来的纯 API 模式)使用:
	// 正常运行时根路径是访客前台,由 theme 模块接管。
	FallbackRootToConsole bool
	// InstallRedirect 非空时(首次安装向导模式)把站点入口重定向到该地址。
	//
	// 站长此时打开浏览器应当看到安装向导,而不是一个登不进去的登录页。
	// 拦的只是入口,/console/assets/* 照常提供 —— 向导自己也跑在这个 SPA 里。
	InstallRedirect string
}

Options 是构造路由所需的依赖。

type Server

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

Server 包装 http.Server 与其生命周期管理。

func New

func New(handler http.Handler, cfg *config.ServerConfig, logger *slog.Logger) *Server

New 构造 Server。

func (*Server) Run

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

Run 启动服务并阻塞,直到 ctx 被取消或服务异常退出。

ctx 取消后停止接收新连接,并给在途请求留出 ShutdownTimeout 的收尾时间。

Jump to

Keyboard shortcuts

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