跳转到内容

core — API 快速参考

本页列出 github.com/spcent/plumego/core 导出的每个公开符号。已熟悉该包时用本页快速查阅;需要边界说明和使用模式时请读 Core Primer

import "github.com/spcent/plumego/core"

type AppConfig struct {
Addr string
TLS TLSConfig
Router RouterConfig
ReadTimeout time.Duration
ReadHeaderTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
MaxHeaderBytes int
HTTP2Enabled bool
DrainInterval time.Duration
}
type TLSConfig struct {
Enabled bool
CertFile string
KeyFile string
}
type RouterConfig struct {
MethodNotAllowed bool
}
type AppDependencies struct {
Logger log.StructuredLogger
}
type App struct { /* unexported fields */ }

func New(cfg AppConfig, deps AppDependencies) *App

创建并返回新的 Appcfg 通常来自 DefaultConfig() 并按需覆盖字段。deps 携带可选共享依赖(Logger);省略时日志会被丢弃。

func DefaultConfig() AppConfig

返回可直接使用的 AppConfig,带有面向生产的默认值。

字段默认值
Addr:8080
TLS.Enabledfalse
Router.MethodNotAllowedfalse
ReadTimeout30s
ReadHeaderTimeout5s
WriteTimeout30s
IdleTimeout60s
MaxHeaderBytes1 MiB(1 048 576 bytes)
HTTP2Enabledtrue
DrainInterval500ms

所有路由注册方法都在 *App 上。每个方法都会返回已注册的 *router.Route(调用方通常会丢弃该返回值)。

func (a *App) Get(path string, handler http.Handler) *router.Route
func (a *App) Post(path string, handler http.Handler) *router.Route
func (a *App) Put(path string, handler http.Handler) *router.Route
func (a *App) Delete(path string, handler http.Handler) *router.Route
func (a *App) Patch(path string, handler http.Handler) *router.Route
func (a *App) Any(path string, handler http.Handler) *router.Route

为给定路径注册所有 HTTP 方法的处理器。

func (a *App) AddRoute(method, path string, handler http.Handler, opts ...router.RouteOption) *router.Route

低层路由注册方法。opts 可接收 router.WithRouteName(name) 以启用反向查找。

func (a *App) Group(prefix string) *router.Group

返回一个路由分组;在该分组上注册的所有路由都会自动加上 prefix 前缀。

func (a *App) Handle(path string, handler http.Handler) *router.Route

在给定路径注册一个 http.Handler(任意方法)。


func (a *App) Use(middlewares ...func(http.Handler) http.Handler)

把中间件追加到处理链。必须在 Prepare 之前调用。中间件按注册顺序运行(最先注册的位于最外层)。


func (a *App) URL(name string, pairs ...string) string

把命名路由解析为 URL。pairs 以参数名和值交替传入:app.URL("user-detail", "id", "42") -> "/api/users/42"。如果路由名称不存在或参数数量错误,会 panic。


func (a *App) Prepare() error

冻结路由表、应用中间件,并构建处理链。必须在 Server 之前调用。配置无效时返回非 nil 错误。

func (a *App) Server() (*http.Server, error)

返回配置好的 *http.Server。必须在 Prepare 之后调用。调用方负责 ListenAndServeListenAndServeTLSShutdown

func (a *App) Run()

合并便利路径:调用 Prepare,然后通过 ListenAndServe 启动服务器(TLS 启用时调用 ListenAndServeTLS)。失败时记录 fatal 日志并退出。需要在启动前检查 server 时,请使用 Prepare + Server

func (a *App) Shutdown(ctx context.Context) error

发起优雅停机。按 DrainInterval 间隔排空飞行中的连接,直到 ctx 取消或所有连接排空。调用时应传入带截止时间的 context。


func (a *App) Logger() log.StructuredLogger

返回通过 AppDependencies 注入的 logger。未提供 logger 时返回 no-op logger。

func (a *App) Router() *router.Router

返回底层的 *router.Router。当需要直接调用 router 上的 StaticStaticFSGroup 时使用。


语法匹配内容读取方式
:name单个路径段router.Param(r, "name")
*name剩余所有路径段router.Param(r, "name")