routes

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2026 License: MIT Imports: 10 Imported by: 0

README

http/routes

http/routes keeps route metadata next to handlers and mounts the result on chi.

Use routes.Blueprint in normal application code. It keeps handlers, metadata, tags, and middleware in one place, and makes child route inclusion explicit.

Use lower-level routes.Route and routes.Mount when routes are generated, adapted from another router, or when you need direct control over the route slice. Blueprint builds the same route data; it is not a second routing system.

Blueprint uses a handler-required registration shape: methods take path, summary, a required handler built with routes.Func or routes.Handler, then route options. Prefer routes.Func(fn) for plain http.HandlerFunc values and methods; use routes.Handler(h) only when middleware or an adapter already returned an http.Handler.

Blueprint

bearer, err := authhttp.RequireBearer(manager)
if err != nil {
	return err
}

updater := routes.NewBlueprint(
	routes.DefaultTags("updater"),
	routes.DefaultAuth(routes.AuthRequired),
	routes.DefaultMiddleware(bearer),
)
updater.Post(
	"/refresh",
	"Refresh updater state",
	routes.Func(refresh),
)

api := routes.NewBlueprint()
api.Include("/updater", updater)

err = api.MountAt(r, "/api")

Blueprint.Routes() returns owned []routes.Route copies, so callers can still export or mount through the lower-level functions.

AuthPublic, AuthOptional, and AuthRequired are exported as route metadata. Mount also guards AuthRequired routes at runtime, so auth middleware must mark successful requests with routes.WithAuthenticated.

Lower Level

routes.Mount(r, "/api", []routes.Route{
	{
		Method:     http.MethodGet,
		Path:       "/status",
		Summary:    "Get status",
		Auth:       routes.AuthRequired,
		Handler:    http.HandlerFunc(status),
		Middleware: []routes.Middleware{bearer},
	},
})

Use routes.ExportJSON, routes.ExportMarkdown, or routes.ExportOpenAPI when the same route declarations should also produce metadata.

spec, err := routes.ExportOpenAPI(api.Routes(), routes.OpenAPIOptions{
	Title:   "Updater API",
	Version: "1.0.0",
})

Documentation

Overview

Package routes provides declarative route definitions and middleware composition. Package routes 提供声明式路由定义与中间件组合。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Authenticated added in v0.1.9

func Authenticated(ctx context.Context) bool

Authenticated reports whether ctx was marked by WithAuthenticated. Authenticated 返回 ctx 是否已由 WithAuthenticated 标记。

func ExportJSON

func ExportJSON(routes []Route) ([]byte, error)

ExportJSON returns route metadata as JSON. ExportJSON 返回 JSON 路由元数据。

func ExportMarkdown

func ExportMarkdown(routes []Route) (string, error)

ExportMarkdown returns a Markdown route table. ExportMarkdown 返回 Markdown 路由表。

func ExportOpenAPI added in v0.1.9

func ExportOpenAPI(routes []Route, opts OpenAPIOptions) ([]byte, error)

ExportOpenAPI returns OpenAPI 3.0 JSON from route metadata. ExportOpenAPI 根据路由元数据返回 OpenAPI 3.0 JSON。

func Func added in v0.1.7

func Func(fn http.HandlerFunc) handlerSpec

Func builds the required Blueprint handler from an http.HandlerFunc. This is the preferred option for plain handler functions and methods. Panics if fn is nil. Func 使用 http.HandlerFunc 构造 Blueprint 必填 handler。 这是普通 handler 函数和方法值的首选写法。 fn 为 nil 时会 panic。

func Handler added in v0.1.7

func Handler(h http.Handler) handlerSpec

Handler builds the required Blueprint handler from an existing http.Handler. Prefer Func for plain http.HandlerFunc values and methods. Panics if h is nil, including typed-nil handlers. Handler 使用现成的 http.Handler 构造 Blueprint 必填 handler。 普通 http.HandlerFunc 或方法值优先用 Func。 h 为 nil 时会 panic,包括 typed-nil handler。

func Mount

func Mount(r chi.Router, prefix string, routes []Route) error

Mount registers routes on r. Mount does not mutate routes. Mount 在 r 上注册路由。 Mount 不会修改 routes。

func WithAuthenticated added in v0.1.9

func WithAuthenticated(ctx context.Context) context.Context

WithAuthenticated marks ctx as authenticated. Auth middleware should call it after credentials are accepted. WithAuthenticated 将 ctx 标记为已认证。 认证中间件应在凭据通过后调用它。

Types

type AuthRequirement added in v0.1.7

type AuthRequirement string

AuthRequirement is the exported authentication requirement for a route. Mount guards AuthRequired routes at runtime. AuthRequirement 表示导出的路由认证要求。 Mount 会在运行时保护 AuthRequired 路由。

const (
	// AuthPublic means no authentication is required.
	// AuthPublic 表示不要求认证。
	AuthPublic AuthRequirement = "public"
	// AuthOptional means authentication may be supplied but is not required.
	// AuthOptional 表示可以提供认证但不强制要求。
	AuthOptional AuthRequirement = "optional"
	// AuthRequired means authentication is required.
	// AuthRequired 表示必须认证。
	AuthRequired AuthRequirement = "required"
)

type Blueprint

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

Blueprint groups routes and route defaults. Call NewBlueprint, add routes with Get/Post/... , then mount with Mount or MountAt. Nil Blueprint is invalid and panics on use. Blueprint 分组管理路由及默认配置。 调用 NewBlueprint,使用 Get/Post/... 添加路由,再通过 Mount 或 MountAt 挂载。 Nil Blueprint 无效,使用时会 panic。

func NewBlueprint

func NewBlueprint(opts ...BlueprintOption) *Blueprint

NewBlueprint returns an empty Blueprint. NewBlueprint 返回空 Blueprint。

func (*Blueprint) Add

func (b *Blueprint) Add(routeList ...Route)

Add adds routes. The blueprint keeps its own copies. Add 添加路由。 Blueprint 会保留自己的副本。

func (*Blueprint) Delete

func (b *Blueprint) Delete(path, summary string, spec handlerSpec, opts ...RouteOption)

Delete adds a DELETE route. Delete 添加 DELETE 路由。

func (*Blueprint) ExportJSON

func (b *Blueprint) ExportJSON() ([]byte, error)

ExportJSON exports route metadata as JSON. ExportJSON 将路由元数据导出为 JSON。

func (*Blueprint) ExportMarkdown

func (b *Blueprint) ExportMarkdown() (string, error)

ExportMarkdown exports route metadata as Markdown. ExportMarkdown 将路由元数据导出为 Markdown。

func (*Blueprint) ExportOpenAPI added in v0.1.9

func (b *Blueprint) ExportOpenAPI(opts OpenAPIOptions) ([]byte, error)

ExportOpenAPI exports route metadata as OpenAPI 3.0 JSON. ExportOpenAPI 将路由元数据导出为 OpenAPI 3.0 JSON。

func (*Blueprint) Get

func (b *Blueprint) Get(path, summary string, spec handlerSpec, opts ...RouteOption)

Get adds a GET route. Get 添加 GET 路由。

func (*Blueprint) Handle

func (b *Blueprint) Handle(method, path, summary string, spec handlerSpec, opts ...RouteOption)

Handle adds a route. The handler is required as the fourth argument. Panics if spec is invalid. Handle 添加路由。 第四个参数必须提供 handler。 spec 非法时会 panic。

func (*Blueprint) Include

func (b *Blueprint) Include(prefix string, child *Blueprint, opts ...IncludeOption)

Include adds child routes under prefix. Include 在 prefix 下添加子路由。

func (*Blueprint) Mount

func (b *Blueprint) Mount(router chi.Router) error

Mount registers the routes on router. Mount 在 router 上注册路由。

func (*Blueprint) MountAt

func (b *Blueprint) MountAt(router chi.Router, prefix string) error

MountAt registers the routes under prefix. MountAt 在 prefix 下注册路由。

func (*Blueprint) Patch

func (b *Blueprint) Patch(path, summary string, spec handlerSpec, opts ...RouteOption)

Patch adds a PATCH route. Patch 添加 PATCH 路由。

func (*Blueprint) Post

func (b *Blueprint) Post(path, summary string, spec handlerSpec, opts ...RouteOption)

Post adds a POST route. Post 添加 POST 路由。

func (*Blueprint) Put

func (b *Blueprint) Put(path, summary string, spec handlerSpec, opts ...RouteOption)

Put adds a PUT route. Put 添加 PUT 路由。

func (*Blueprint) Routes

func (b *Blueprint) Routes() []Route

Routes returns a copy of the routes. Routes 返回路由副本。

type BlueprintOption

type BlueprintOption func(*blueprintConfig)

BlueprintOption configures defaults for routes added to a Blueprint. BlueprintOption 配置 Blueprint 中新增路由的默认值。

func DefaultAuth

func DefaultAuth(auth AuthRequirement) BlueprintOption

DefaultAuth sets the default auth requirement. AuthRequired routes require authenticated context at runtime. DefaultAuth 设置默认认证要求。 AuthRequired 路由运行时要求已认证 context。

func DefaultMiddleware

func DefaultMiddleware(mw ...Middleware) BlueprintOption

DefaultMiddleware prepends middleware to routes added to a Blueprint. DefaultMiddleware 为 Blueprint 中新增路由预置最外层中间件。

func DefaultTags

func DefaultTags(tags ...string) BlueprintOption

DefaultTags prepends tags to routes added to a Blueprint. DefaultTags 为 Blueprint 中新增路由预置 tags。

type IncludeOption

type IncludeOption func(*includeConfig)

IncludeOption modifies child routes during Include. IncludeOption 在 Include 时修改子路由。

func IncludeAuth

func IncludeAuth(auth AuthRequirement) IncludeOption

IncludeAuth sets the auth requirement on included routes. AuthRequired routes require authenticated context at runtime. IncludeAuth 为 include 的路由设置认证要求。 AuthRequired 路由运行时要求已认证 context。

func IncludeMiddleware

func IncludeMiddleware(mw ...Middleware) IncludeOption

IncludeMiddleware prepends middleware to included routes. IncludeMiddleware 为 include 的路由预置最外层中间件。

func IncludeTags

func IncludeTags(tags ...string) IncludeOption

IncludeTags appends tags to included routes. IncludeTags 为 include 的路由追加 tags。

type Middleware

type Middleware = func(http.Handler) http.Handler

Middleware is a chi-compatible middleware. Middleware 是兼容 chi 的中间件。

type OpenAPIOptions added in v0.1.9

type OpenAPIOptions struct {
	// Title is the OpenAPI info title.
	// Title 是 OpenAPI info title。
	Title string
	// Version is the OpenAPI info version.
	// Version 是 OpenAPI info version。
	Version string
	// Description is the optional OpenAPI info description.
	// Description 是可选的 OpenAPI info description。
	Description string
	// BearerSecurityScheme is the bearer auth security scheme name.
	// BearerSecurityScheme 是 bearer auth security scheme 名。
	BearerSecurityScheme string
}

OpenAPIOptions configures ExportOpenAPI. OpenAPIOptions 配置 ExportOpenAPI。

type Route

type Route struct {
	Method     string
	Path       string
	Summary    string
	Tags       []string
	Auth       AuthRequirement
	Handler    http.Handler
	Middleware []Middleware
}

Route defines an HTTP endpoint. Pass routes to Mount. Route 定义 HTTP 端点。 使用 Mount 挂载路由。

func WithMiddleware

func WithMiddleware(routes []Route, mws ...Middleware) []Route

WithMiddleware returns routes with prepended middleware. WithMiddleware 返回预置最外层中间件后的路由副本。

func WithPrefix

func WithPrefix(prefix string, routes []Route) []Route

WithPrefix returns routes with prefix applied. WithPrefix 返回添加 prefix 后的路由副本。

func WithTags

func WithTags(routes []Route, tags ...string) []Route

WithTags returns routes with tags appended. WithTags 返回追加 tags 后的路由副本。

func (Route) Clone

func (r Route) Clone() Route

Clone returns a copy of r. Clone 返回 r 的副本。

type RouteOption

type RouteOption func(*Route)

RouteOption modifies a route before it is added. RouteOption 在路由加入前修改路由。

func Auth

func Auth(auth AuthRequirement) RouteOption

Auth sets Route.Auth. AuthRequired routes require authenticated context at runtime. Auth 设置 Route.Auth。 AuthRequired 路由运行时要求已认证 context。

func Tags

func Tags(tags ...string) RouteOption

Tags appends Route.Tags. Tags 追加 Route.Tags。

func Use

func Use(mw ...Middleware) RouteOption

Use appends route middleware. Use 追加路由中间件。

type Router

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

Router collects routes under prefixes. Build routes at startup. Nil Router is invalid and panics on use. Router 收集并组织带前缀的路由。 请在启动阶段构建路由。 Nil Router 无效,使用时会 panic。

func NewRouter

func NewRouter() *Router

NewRouter returns an empty Router. NewRouter 返回空 Router。

func (*Router) ExportJSON

func (r *Router) ExportJSON() ([]byte, error)

ExportJSON exports route metadata as JSON. ExportJSON 导出 JSON 路由元数据。

func (*Router) ExportMarkdown

func (r *Router) ExportMarkdown() (string, error)

ExportMarkdown exports route metadata as Markdown. ExportMarkdown 导出 Markdown 路由表。

func (*Router) Include

func (r *Router) Include(prefix string, routes []Route)

Include adds routes under prefix. Include 在 prefix 下添加路由。

func (*Router) Mount

func (r *Router) Mount(router chi.Router, prefix string) error

Mount registers the routes on router. Mount 在 router 上注册路由。

func (*Router) Routes

func (r *Router) Routes() []Route

Routes returns a copy of the routes. Routes 返回路由副本。

Jump to

Keyboard shortcuts

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