Routes and requests
This page explains how Behemoth's routes reach your application, which settings shape them, and how a failed request is answered. Read How Behemoth fits together first.
Behemoth does not run an HTTP server. You create your router and start your server as you always do. Behemoth adds its routes to your router and changes nothing else on it: no middleware, no error handler, no server settings.
Router adapters #
An adapter connects Behemoth to one router. Pass the adapter to BootConfig.HTTP, and Boot mounts the routes of every plugin on it. The following adapters exist. Each import path starts with github.com/go-behemoth/behemoth/plugins/adapters/:
| Router | Package | Constructor takes |
|---|---|---|
net/http | nethttp (part of Behemoth) | A *http.ServeMux |
| Gin | gin | A *gin.Engine or a *gin.RouterGroup |
| Echo v5 | echo | An *echo.Echo |
| chi v5 | chi | A chi.Router: a mux, a group, or a route |
| Fiber v3 | fiber | A *fiber.App |
Every adapter has one function, New. The framework adapters are separate modules, so you download Gin only if you use Gin. For any other framework, implement the FrameworkDriver interface.
mux := http.NewServeMux()
// Register your own routes before Boot.
mux.HandleFunc("GET /{$}", home)
ac, err := engine.Boot(
ctx,
app,
db,
engine.BootConfig{
Crypto: cryptoCfg,
HTTP: nethttp.New(mux),
},
)
if err != nil {
log.Fatal(err)
}
log.Fatal(http.ListenAndServe(":8080", mux))Keep the following rules in mind:
- Register your own routes before
Boot. If one of them has the same method and path as a Behemoth route,Bootreturns an error and leaves your route as it was. - Leave
HTTPunset to skip serving.Bootstill builds and checks the routes. Use this in a worker or a command-line tool. - Each framework has details of its own. The Routers reference covers route conflicts on
net/http, middleware order on Fiber, and groups on Gin and chi.
Where routes live #
Behemoth mounts every route under a base path, /api/auth by default. A plugin can add a mount path of its own below it. For example, the email and password plugin serves POST /api/auth/sign-up/email and POST /api/auth/sign-in/email. Change the base path with RouterConfig.BasePath.
A route that a plugin returns from its Routes method has a method, a path, a handler, and optional middleware. Write a path parameter as {name} and read it with rctx.Param("name"), whatever the router. Each adapter translates the syntax.
Router settings #
Set the following fields in BootConfig.Router, a httpapi.RouterConfig. All of them are optional:
| Field | Default | What it controls |
|---|---|---|
BasePath | /api/auth | Where the routes are mounted. |
BaseURL | Empty | The origin a browser reaches Behemoth at. Set it in production. |
TrustedOrigins | Empty | Other origins, such as a front end on another host, that may call Behemoth and receive redirects. |
TrustedProxies | Empty | The load balancers or reverse proxies allowed to tell Behemoth the client's address. |
ClientIPHeader | X-Forwarded-For | The header that carries the client's address when a trusted proxy sets it. |
RequestIDHeader | X-Request-ID | The header that carries a request's ID. |
Carrier | An HttpOnly, Secure cookie | How the session token travels. See Token delivery. |
ErrorMapper | DefaultErrorMapper | The status and body of a failed request. See Change the error body. |
The client's address #
Behemoth uses the client's address for rate limits, audit events, and the optional record on a session. By default it is the address of the direct peer. Behind a load balancer, the direct peer is the balancer, so every client would share one address.
List the address blocks of your proxies in RouterConfig.TrustedProxies. Behemoth then reads the client's address from ClientIPHeader, but only on requests that come from one of those blocks. Without it, one client's failed sign-ins can rate-limit every user behind the same proxy. Boot logs a warning when you set ClientIPHeader without TrustedProxies, because the header is then ignored.
Request IDs #
Every request has an ID. Behemoth reads it from the X-Request-ID header when the value is usable, and generates one otherwise. It returns the ID in the same header of every response, including errors, and writes it on the log lines of the request. A user who reports a problem can quote the ID, and you can find the matching logs.
Errors #
A failed request is answered with a status and a JSON body:
{"error": "session expired", "code": "session_expired"}The error field is a message that is safe to show. The code field is a stable string that your client can match on, for example session_expired, email_invalid_input, rate_limited, or untrusted_origin. Each plugin's page lists the errors of its routes.
Categories and statuses #
Inside Behemoth, every expected failure is an *errs.DomainError with a category, a code, and a message. The category decides the HTTP status:
| Category | Status | Meaning |
|---|---|---|
validation | 400 | The input is not acceptable. |
unauthorized, session, token | 401 | The caller is not signed in, or the session or token is not usable. |
forbidden | 403 | The caller is signed in but not allowed. |
not_found | 404 | The thing does not exist. |
duplicate_key, foreign_key_violation, conflict | 409 | The request collides with existing data or a concurrent change. |
unsupported_media_type | 415 | The body is of a type the route does not accept. |
rate_limited | 429 | The caller made too many attempts. The response has a Retry-After header. |
unavailable | 503 | The system has no room right now, for example when too many passwords are being hashed. A later attempt may succeed. |
| Every other category | 500 | A failure of the system, such as a lost database connection. |
A 500 response never carries internal detail. The body is {"error": "internal server error"}, and the X-Request-ID header links it to the full error in your logs.
Rejections and failures #
Behemoth also separates two kinds of error. A rejection means the system worked and the caller was refused: a validation error, a conflict, an unauthorized or forbidden request, or a rate limit. Every other category is a failure of the system.
The difference matters in your hook handlers. To refuse an operation, return a typed error from the errs package, such as errs.NewValidationError or errs.NewForbidden. Behemoth counts it as a refused request, fires the failed hook point, and answers with the status of the category. An untyped error counts as a failure of the system. It stops the operation and fires no failed point. See Register a handler.
Read errors in your code #
When you call a flow from code, the same errors come back as Go errors. Check them with errs.IsCategory, errs.IsCode, and errs.IsRejection:
_, err := plugin.SignIn(ctx, creds)
if errs.IsRejection(err) {
// The user was refused. Show the reason.
return err
}
if err != nil {
// A failure of the system. Log it and retry later.
return err
}Change the error body #
To change the shape of the body or the status of a category, set RouterConfig.ErrorMapper to a type that implements httpapi.ErrorMapper. Its Map method takes the error and returns a status and a body. The following mapper wraps the default one and nests its body under an error key:
type envelope struct {
inner *httpapi.DefaultErrorMapper
}
func (m envelope) Map(err error) (int, behemoth.M) {
status, body := m.inner.Map(err)
return status, behemoth.M{"ok": false, "error": body}
}
cfg := engine.BootConfig{
Router: httpapi.RouterConfig{
ErrorMapper: envelope{
inner: &httpapi.DefaultErrorMapper{},
},
},
}Cross-site requests #
When the session token travels in a cookie, Behemoth checks where each state-changing request comes from. It refuses a POST, PUT, PATCH, or DELETE from an origin it does not trust with 403 and the code untrusted_origin, and one with a form content type with 415. A bearer token needs neither check. See Cross-site requests for the rules.
Next steps #
To go deeper, read the following pages:
- Rate limiting: Limit attempts per route or per operation.
- Routers: Details for each framework adapter.
- Sessions and credentials: How the session token travels.
- Telemetry: Logs, request IDs, and metrics.