router

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const ManifestFileName = ".route-manifest.json"

ManifestFileName is the manifest written into the client output directory.

Variables

This section is empty.

Functions

func DeriveName

func DeriveName(method, path string) string

DeriveName builds a stable, readable route name from a method and path for routes that were not explicitly named with .As(). It follows REST conventions:

GET    /api/posts        → api.posts.index
POST   /api/posts        → api.posts.store
GET    /api/posts/{id}   → api.posts.show
PUT    /api/posts/{id}   → api.posts.update
DELETE /api/posts/{id}   → api.posts.destroy
POST   /api/posts/{id}/publish → api.posts.publish.store

Explicit .As("...") names always take precedence over this.

func ParamInt

func ParamInt(c *nhttp.Context, name string) (int, bool)

ParamInt is a helper to extract an integer route parameter. Returns 0, false if the param is missing or not a valid integer.

func ParamInt64

func ParamInt64(c *nhttp.Context, name string) (int64, bool)

ParamInt64 extracts an int64 route parameter.

func PathParams

func PathParams(path string) []string

PathParams returns the parameter names in a route path, supporting both ":id" and "{id}" syntaxes.

func WriteManifest

func WriteManifest(r *Router, outDir string) error

WriteManifest writes the route manifest JSON into outDir. It is called by the app at startup when NIMBUS_DUMP_ROUTES=1, and consumed by `nimbus gen:client`.

Types

type Bindable

type Bindable interface {
	// RouteKey returns the route parameter name to match (e.g. "id", "slug").
	RouteKey() string
	// FindForRoute looks up the model by the given parameter value.
	// Return the found model or an error if not found.
	FindForRoute(value string) (any, error)
}

Bindable is the interface that models must implement to support route model binding. When a route parameter matches the parameter name, the model is automatically resolved from the database and injected into the context store.

Example model:

type User struct {
    database.Model
    Name  string
    Email string
}

func (u *User) RouteKey() string        { return "id" }
func (u *User) FindForRoute(val string) (any, error) {
    var user User
    err := db.Where("id = ?", val).First(&user).Error
    return &user, err
}

type Group

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

Group allows defining routes with a shared prefix and middleware (AdonisJS Route.group).

func (*Group) Any

func (g *Group) Any(path string, handler HandlerFunc) *Route

Any registers a handler for all HTTP methods (prefixed).

func (*Group) Delete

func (g *Group) Delete(path string, handler HandlerFunc) *Route

Delete registers DELETE path (prefixed).

func (*Group) Get

func (g *Group) Get(path string, handler HandlerFunc) *Route

Get registers GET path (prefixed).

func (*Group) Patch

func (g *Group) Patch(path string, handler HandlerFunc) *Route

Patch registers PATCH path (prefixed).

func (*Group) Post

func (g *Group) Post(path string, handler HandlerFunc) *Route

Post registers POST path (prefixed).

func (*Group) Put

func (g *Group) Put(path string, handler HandlerFunc) *Route

Put registers PUT path (prefixed).

func (*Group) Resource

func (g *Group) Resource(name string, ctrl ResourceController, opts ...ResourceOption)

Resource registers RESTful resource routes within this group's prefix.

func (*Group) Use

func (g *Group) Use(m ...Middleware)

Use adds middleware to this group only.

type HandlerFunc

type HandlerFunc func(*http.Context) error

HandlerFunc is the handler signature (AdonisJS controller action style).

type ManifestEntry

type ManifestEntry struct {
	Name   string                  `json:"name"`
	Method string                  `json:"method"`
	Path   string                  `json:"path"`
	Params []string                `json:"params,omitempty"`
	Schema map[string]ManifestRule `json:"schema,omitempty"`
}

ManifestEntry describes a single registered route for code generation (e.g. `nimbus gen:client` → Hive registry).

func Manifest

func Manifest(r *Router) []ManifestEntry

Manifest builds the route manifest for a router. Explicitly named routes keep their name; unnamed routes get a derived one. Names are guaranteed unique — on a collision the HTTP method is appended, then a numeric suffix.

type ManifestRule

type ManifestRule struct {
	Type     string `json:"type"`
	Required bool   `json:"required"`
}

ManifestRule is a body-schema field's generated type info.

type Middleware

type Middleware func(HandlerFunc) HandlerFunc

Middleware runs before/after handlers.

func BindModel

func BindModel(bindings ...ModelBinding) Middleware

BindModel returns middleware that resolves route parameters to models. It inspects the registered bindings, extracts the corresponding URL parameter, calls FindForRoute, and stores the result in the context via c.Set().

Usage:

r.Get("/users/{id}", showUser).
    Use(router.BindModel(router.ModelBinding{
        Param:      "id",
        ContextKey: "user",
        Model:      &User{},
    }))

Then in the handler:

func showUser(c *http.Context) error {
    user := c.MustGet("user").(*User)
    return c.JSON(200, user)
}

func BindModelParam

func BindModelParam(model Bindable) Middleware

BindModelParam is a simpler version that uses the Bindable interface directly. The route parameter is taken from model.RouteKey(), and the context key defaults to the param name with "_model" suffix.

r.Get("/posts/{id}", showPost).Use(router.BindModelParam(&Post{}))

func NameMiddleware

func NameMiddleware(name string, mw Middleware) Middleware

NameMiddleware associates a human-friendly name with a middleware function for observability tooling (e.g. Telescope). It returns the same middleware.

type ModelBinding

type ModelBinding struct {
	// Param is the route parameter name (e.g. "id", "user").
	Param string
	// ContextKey is the key used to store the resolved model in c.Set().
	ContextKey string
	// Model is a Bindable instance used to resolve the model.
	Model Bindable
}

ModelBinding is a route model binding registration.

type ParamMeta

type ParamMeta struct {
	Name        string `json:"name"`
	In          string `json:"in"`   // path, query, header
	Type        string `json:"type"` // string, integer, boolean
	Required    bool   `json:"required"`
	Description string `json:"description,omitempty"`
}

ParamMeta describes a route parameter.

type ResourceController

type ResourceController interface {
	Index(c *http.Context) error   // GET    /posts
	Create(c *http.Context) error  // GET    /posts/create
	Store(c *http.Context) error   // POST   /posts
	Show(c *http.Context) error    // GET    /posts/:id
	Edit(c *http.Context) error    // GET    /posts/:id/edit
	Update(c *http.Context) error  // PUT    /posts/:id
	Destroy(c *http.Context) error // DELETE /posts/:id
}

ResourceController defines the 7 RESTful actions for a resource. Implement all methods on a controller struct, then register with:

app.Router.Resource("posts", &PostsController{})

type ResourceOption

type ResourceOption func(*resourceConfig)

ResourceOption configures which actions to register.

func ApiOnly

func ApiOnly() ResourceOption

ApiOnly excludes the create and edit form routes (useful for JSON APIs).

func Except

func Except(actions ...string) ResourceOption

Except registers all actions except the listed ones.

func Only

func Only(actions ...string) ResourceOption

Only registers only the listed actions. Valid actions: "index", "create", "store", "show", "edit", "update", "destroy".

type Route

type Route struct {
	Meta RouteMeta
	// contains filtered or unexported fields
}

Route represents a registered route and supports chaining (e.g. .As()).

func (*Route) As

func (rt *Route) As(name string) *Route

As assigns a name to this route for URL generation.

app.Router.Get("/users", handler).As("users.index")
app.Router.Get("/users/:id", handler).As("users.show")

func (*Route) Body

func (rt *Route) Body(v any) *Route

Body sets the expected request body type for documentation.

func (*Route) DeprecatedRoute

func (rt *Route) DeprecatedRoute() *Route

DeprecatedRoute marks the route as deprecated.

func (*Route) Describe

func (rt *Route) Describe(summary string) *Route

Describe sets a summary for API documentation.

func (*Route) Method

func (rt *Route) Method() string

Method returns the HTTP method.

func (*Route) Name

func (rt *Route) Name() string

Name returns the route name.

func (*Route) Path

func (rt *Route) Path() string

Path returns the route path.

func (*Route) Returns

func (rt *Route) Returns(status int, v any) *Route

Returns sets the expected response type for documentation.

func (*Route) Schema

func (rt *Route) Schema(s validation.Schema) *Route

Schema registers a validation.Schema for this route so gen:client can reflect the field types and generate TypeScript interfaces.

router.Post("/posts", handler).As("posts.store").Schema(postSchema)

func (*Route) Secure

func (rt *Route) Secure(schemes ...string) *Route

Secure marks the route as requiring authentication.

func (*Route) Tag

func (rt *Route) Tag(tags ...string) *Route

Tag adds tags for API documentation grouping.

type RouteMeta

type RouteMeta struct {
	Summary     string            `json:"summary,omitempty"`
	Description string            `json:"description,omitempty"`
	Tags        []string          `json:"tags,omitempty"`
	Deprecated  bool              `json:"deprecated,omitempty"`
	RequestBody any               `json:"request_body,omitempty"` // struct type for body
	BodySchema  validation.Schema `json:"body_schema,omitempty"`  // typed schema for gen:client
	Response    any               `json:"response,omitempty"`     // struct type for response
	Responses   map[int]any       `json:"responses,omitempty"`    // status -> struct
	Params      []ParamMeta       `json:"params,omitempty"`
	Headers     map[string]string `json:"headers,omitempty"`
	Security    []string          `json:"security,omitempty"`
}

RouteMeta holds route metadata for documentation and OpenAPI generation.

type Router

type Router struct {
	Container http.Container
	// contains filtered or unexported fields
}

Router wraps Chi as the HTTP router (solid, net/http compatible).

func New

func New() *Router

New creates a new Router backed by Chi.

func (*Router) Any

func (r *Router) Any(path string, handler HandlerFunc) *Route

Any registers a route that matches all standard HTTP methods.

func (*Router) Delete

func (r *Router) Delete(path string, handler HandlerFunc) *Route

Delete registers a DELETE route.

func (*Router) Fallback

func (r *Router) Fallback(handler HandlerFunc)

Fallback registers a catch-all handler that is invoked when no routes match. This is the equivalent of AdonisJS's Route.fallback(). If no Fallback is registered, Chi's default 404 handling applies.

app.Router.Fallback(func(c *http.Context) error {
    return c.JSON(404, map[string]string{"error": "Not found"})
})

func (*Router) Get

func (r *Router) Get(path string, handler HandlerFunc) *Route

Get registers a GET route.

func (*Router) Group

func (r *Router) Group(prefix string, middleware ...Middleware) *Group

Group returns a group that shares a path prefix and optional middleware.

func (*Router) Mount

func (r *Router) Mount(path string, handler http.Handler)

Mount attaches an http.Handler at the given path. Useful for mounting sub-applications (e.g. MCP servers, SSE endpoints) that implement http.Handler.

func (*Router) Patch

func (r *Router) Patch(path string, handler HandlerFunc) *Route

Patch registers a PATCH route.

func (*Router) Post

func (r *Router) Post(path string, handler HandlerFunc) *Route

Post registers a POST route.

func (*Router) PrintRoutes

func (r *Router) PrintRoutes(w io.Writer)

PrintRoutes prints a formatted table of all registered routes. If w is nil, it prints to os.Stdout.

func (*Router) Put

func (r *Router) Put(path string, handler HandlerFunc) *Route

Put registers a PUT route.

func (*Router) Resource

func (r *Router) Resource(name string, ctrl ResourceController, opts ...ResourceOption)

Resource registers RESTful resource routes for a controller. Generates: index, create, store, show, edit, update, destroy.

func (*Router) Route

func (r *Router) Route(path string, methods []string, handler HandlerFunc) *Route

Route registers a handler for the given custom HTTP methods.

func (*Router) Routes

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

Routes returns all registered routes.

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements http.Handler.

func (*Router) URL

func (r *Router) URL(name string, params ...string) string

URL generates a URL for a named route, substituting params. Params are key-value pairs: router.URL("users.show", "id", "42") → "/users/42".

func (*Router) Use

func (r *Router) Use(m ...Middleware)

Use adds global middleware (like AdonisJS start/kernel).

type StatusError

type StatusError interface {
	error
	HTTPStatus() int
}

StatusError is implemented by errors that carry an HTTP status code, letting the router honor that status without importing the errors package. Both errors.HTTPError and errors.AppError satisfy it.

Jump to

Keyboard shortcuts

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