Documentation
¶
Overview ¶
Package trilha is a file-based web framework for Go: pages, layouts, API routes and middleware are discovered from the app/ directory tree by the trilha CLI, which generates a typed registration file; this package is the runtime those generated files call into.
Index ¶
- Constants
- Variables
- func CSRFInput(c *Ctx) h.Node
- func CompileErrorPage(output string) string
- func Errorf(code int, format string, a ...any) error
- func Fatal(err error)
- func PublicFS(embedded fs.FS, dir string) fs.FS
- func Redirect(url string) error
- func RedirectCode(url string, code int) error
- type App
- func (a *App) Env() Env
- func (a *App) Handler() http.Handler
- func (a *App) ListenAndServe() error
- func (a *App) Logger() *slog.Logger
- func (a *App) Register(r Route)
- func (a *App) Routes() map[string][]string
- func (a *App) SetErrorPage(e ErrorPageFunc)
- func (a *App) SetNotFound(p PageFunc)
- func (a *App) SetRootLayout(l LayoutFunc)
- func (a *App) Values() map[string]any
- type Config
- type Ctx
- func (c *Ctx) App() *App
- func (c *Ctx) BindJSON(v any) error
- func (c *Ctx) CSRFToken() string
- func (c *Ctx) Context() context.Context
- func (c *Ctx) Cookie(name string) (*http.Cookie, error)
- func (c *Ctx) Env() Env
- func (c *Ctx) Form(name string) string
- func (c *Ctx) FormErr() error
- func (c *Ctx) Get(key string) any
- func (c *Ctx) HTML(code int, n h.Node) error
- func (c *Ctx) Header(k, v string)
- func (c *Ctx) JSON(code int, v any) error
- func (c *Ctx) Param(name string) string
- func (c *Ctx) Query(name string) string
- func (c *Ctx) Redirect(url string) error
- func (c *Ctx) Request() *http.Request
- func (c *Ctx) RequestID() string
- func (c *Ctx) Set(key string, v any)
- func (c *Ctx) SetCookie(ck *http.Cookie)
- func (c *Ctx) SetTitle(t string)
- func (c *Ctx) Status(code int)
- func (c *Ctx) Text(code int, s string) error
- func (c *Ctx) Title() string
- func (c *Ctx) Writer() http.ResponseWriter
- func (c *Ctx) Written() bool
- type Env
- type ErrorPageFunc
- type HTTPError
- type HandlerFunc
- type LayoutFunc
- type MiddlewareFunc
- type Next
- type PageFunc
- type RedirectError
- type Route
Constants ¶
const CSRFCookie = "trilha_csrf"
CSRFCookie is the name of the double-submit cookie.
const CSRFField = "_csrf"
CSRFField is the hidden form field name.
const CSRFHeader = "X-CSRF-Token"
CSRFHeader is the header accepted instead of the form field.
Variables ¶
var ErrNotFound = errors.New("trilha: not found")
ErrNotFound makes the framework respond with 404 using the app's not-found page (HTML routes) or a JSON error (API routes).
Functions ¶
func CSRFInput ¶
CSRFInput renders the hidden input for forms: h.Form(..., trilha.CSRFInput(c), ...).
func CompileErrorPage ¶
compileErrorPage is used by the CLI dev server; exported for reuse.
func Fatal ¶
func Fatal(err error)
Fatal logs a fatal error and exits, ignoring the normal server-closed error.
func PublicFS ¶
PublicFS returns the static file system for the public directory: the embedded copy in prod, the on-disk directory in dev (so edits show up without a rebuild).
func RedirectCode ¶
RedirectCode returns a redirect error with a custom 3xx status.
Types ¶
type App ¶
type App struct {
// contains filtered or unexported fields
}
App is a configured Trilha application.
func (*App) ListenAndServe ¶
ListenAndServe serves until SIGINT/SIGTERM, then shuts down gracefully.
func (*App) SetErrorPage ¶
func (a *App) SetErrorPage(e ErrorPageFunc)
SetErrorPage sets the page rendered on 500 (app/error.go).
func (*App) SetNotFound ¶
SetNotFound sets the page rendered on 404 (app/not_found.go).
func (*App) SetRootLayout ¶
func (a *App) SetRootLayout(l LayoutFunc)
SetRootLayout sets the layout used by the not-found and error pages.
type Config ¶
type Config struct {
// Addr is the listen address (default ":3000").
Addr string
// Env selects dev (stack traces, live reload, no static cache) or prod.
Env Env
// MaxBodyBytes limits request bodies (default 1 MiB).
MaxBodyBytes int64
// Logger receives structured request logs (default slog.Default()).
Logger *slog.Logger
// Public serves static files at the root. nil disables static files.
Public fs.FS
// CSRFForAPI also enforces CSRF tokens on route.go handlers.
CSRFForAPI bool
}
Config configures an App.
func ConfigFromEnv ¶
func ConfigFromEnv() Config
ConfigFromEnv builds a Config from ADDR/PORT and TRILHA_ENV.
type Ctx ¶
type Ctx struct {
// contains filtered or unexported fields
}
Ctx wraps one request/response pair. It is created per request and is not safe for use from other goroutines after the handler returns.
func (*Ctx) BindJSON ¶
BindJSON decodes the request body into v. Returns an HTTPError 400 on malformed JSON and 413 when the body exceeds the limit.
func (*Ctx) CSRFToken ¶
CSRFToken returns the request's CSRF token, creating the cookie on first use. Put it in forms with CSRFInput or send it in the X-CSRF-Token header.
func (*Ctx) Form ¶
Form returns a form field (POST body or query string). Returns "" if the form cannot be parsed; use FormErr to distinguish.
func (*Ctx) Writer ¶
func (c *Ctx) Writer() http.ResponseWriter
Writer returns the underlying http.ResponseWriter.
type ErrorPageFunc ¶
ErrorPageFunc renders the 500 page (error.go: Error).
type HandlerFunc ¶
HandlerFunc handles an API method or a form submission.
type LayoutFunc ¶
LayoutFunc wraps rendered children (layout.go: Layout).
type MiddlewareFunc ¶
MiddlewareFunc intercepts a subtree (middleware.go: Middleware).
type RedirectError ¶
RedirectError is returned by handlers to redirect the client.
func (*RedirectError) Error ¶
func (e *RedirectError) Error() string
type Route ¶
type Route struct {
// Pattern is the path pattern, e.g. "/blog/{slug}" or "/docs/{path...}".
Pattern string
// Page renders GET for page routes; nil for API routes.
Page PageFunc
// Methods maps HTTP methods to handlers (route.go, or form methods in page.go).
Methods map[string]HandlerFunc
// Layouts wrap the page, innermost first.
Layouts []LayoutFunc
// Middlewares run before the handler, outermost first.
Middlewares []MiddlewareFunc
}
Route is one entry produced by the generator for App.Register.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
trilha
command
Command trilha is the CLI: new, gen, dev, build, routes.
|
Command trilha is the CLI: new, gen, dev, build, routes. |
|
examples
|
|
|
blog
command
|
|
|
blog/app/api/posts
Package posts exposes the JSON API at /api/posts.
|
Package posts exposes the JSON API at /api/posts. |
|
blog/app/marketing-
Package marketing is a route group: its layout wraps /precos and /sobre without adding a URL segment (folder name ends with "-").
|
Package marketing is a route group: its layout wraps /precos and /sobre without adding a URL segment (folder name ends with "-"). |
|
blog/app/painel-
Package painel is a route group for the app area (/painel, /relatorio).
|
Package painel is a route group for the app area (/painel, /relatorio). |
|
blog/app/painel-/relatorio
Package relatorio renders a page from an html/template file instead of the h DSL, using the tmpl adapter.
|
Package relatorio renders a page from an html/template file instead of the h DSL, using the tmpl adapter. |
|
blog/internal/posts
Package posts is an in-memory post store for the example app.
|
Package posts is an in-memory post store for the example app. |
|
Package h is a small, dependency-free HTML DSL: every element, attribute and piece of text is a Node that knows how to render itself to an io.Writer.
|
Package h is a small, dependency-free HTML DSL: every element, attribute and piece of text is a Node that knows how to render itself to an io.Writer. |
|
internal
|
|
|
dev
Package dev implements `trilha dev`: a polling file watcher, a builder and a supervisor that runs the app behind a reverse proxy with live reload.
|
Package dev implements `trilha dev`: a polling file watcher, a builder and a supervisor that runs the app behind a reverse proxy with live reload. |
|
gen
Package gen turns a scan.Result into the source of trilha_gen.go.
|
Package gen turns a scan.Result into the source of trilha_gen.go. |
|
scaffold
Package scaffold writes a new project from embedded templates.
|
Package scaffold writes a new project from embedded templates. |
|
scan
Package scan walks an app/ directory and turns its file conventions into a list of routes, validating them along the way.
|
Package scan walks an app/ directory and turns its file conventions into a list of routes, validating them along the way. |
|
Package tmpl adapts html/template to the h.Node pipeline, for developers who prefer template files over the Go DSL.
|
Package tmpl adapts html/template to the h.Node pipeline, for developers who prefer template files over the Go DSL. |