Documentation
¶
Overview ¶
Package web provides HTTP utilities for lix applications.
Form Handling ¶
The Form type is in the web/form subpackage:
cs := changeset.Cast[User](nil, params, []string{"name", "email"})
cs.ValidateRequired("name", "email")
import "codeberg.org/lixgo/lix/web/form"
f := form.ToForm(cs, "user")
// In templates:
// form.Value("name") - get field value
// form.Error("name") - get error message (respects touched state)
// form.HasError("name") - check if field has visible error
// form.InputName("name") - "user[name]"
// form.InputID("name") - "user_name"
// form.Field("name") - get complete Field struct with all info
Field Configuration ¶
Customize fields with ConfigureField:
f := form.ToForm(cs, "user").
ConfigureField("email", form.Placeholder("[email protected]")).
ConfigureField("bio", form.Label("Biography"), form.InputType("textarea"))
Form Parsing ¶
Parse extracts form parameters from HTTP requests into nested maps:
params, err := web.Parse(r) // "user[name]" -> params["user"]["name"] // "user[address][city]" -> params["user"]["address"]["city"]
Both bracket notation (user[name]) and dot notation (user.name) are supported.
Datastar Validation ¶
For Datastar live validation endpoints:
func HandleValidate(w http.ResponseWriter, r *http.Request) {
err := web.ValidateAndRespond(w, r, (*User)(nil), []string{"name", "email"},
func(cs *changeset.Changeset[User]) *changeset.Changeset[User] {
return cs.ValidateRequired("name", "email").
ValidateFormat("email", emailRegex)
})
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
}
ValidateAndRespond handles the full flow:
- Read Datastar signals from request
- Create changeset and apply validation
- Respect touched state from client
- Send SSE response with validation results
Flash Messages ¶
FlashStore provides cookie-based flash messages:
flash := web.NewFlashStore(secretKey) // In handler after successful action: flash.Set(w, r, "success", "User created!") http.Redirect(w, r, "/users", http.StatusSeeOther) // In next request: flashes := flash.Get(w, r) // map[string][]string // flashes["success"] = ["User created!"] // Messages are auto-cleared after Get
Supported levels: "info", "success", "warning", "error"
Index ¶
- Variables
- func Boot(cfg BootConfig) *echo.Echo
- func MakeErrorHandler(a *assets.Assets, notFound, internalError templ.Component, ...) echo.HTTPErrorHandler
- func Parse(r *http.Request) (map[string]any, error)
- func ParseJSON(r *http.Request) (map[string]any, error)
- func SendValidationResponse[T any](w http.ResponseWriter, r *http.Request, cs *changeset.Changeset[T]) error
- func SetReq(ctx context.Context, r *Req) context.Context
- func Static(e *echo.Echo, prefix string, fs http.FileSystem)
- type BootConfig
- type FlashStore
- type Option
- type Registrar
- type Req
- func (r *Req) AssetPath(logical string) string
- func (r *Req) Assets() *assets.Assets
- func (r *Req) Bind(i interface{}) error
- func (r *Req) Context() context.Context
- func (r *Req) Echo() echo.Context
- func (r *Req) FlashError(msg string)
- func (r *Req) FlashInfo(msg string)
- func (r *Req) FlashSuccess(msg string)
- func (r *Req) FlashWarning(msg string)
- func (r *Req) Flashes() map[string][]string
- func (r *Req) FormValue(name string) string
- func (r *Req) HTML(code int, html string) error
- func (r *Req) Host() string
- func (r *Req) JSON(code int, i interface{}) error
- func (r *Req) NoContent(code int) error
- func (r *Req) Param(name string) string
- func (r *Req) QueryParam(name string) string
- func (r *Req) Redirect(status int, url string) error
- func (r *Req) Render(status int, component templ.Component, opts ...Option) error
- func (r *Req) Request() *http.Request
- func (r *Req) Response() http.ResponseWriter
- func (r *Req) Scheme() string
- func (r *Req) Stream(code int, contentType string, reader io.Reader) error
- func (r *Req) String(status int, s string) error
- type URLOptions
- type ValidationResponse
Constants ¶
This section is empty.
Variables ¶
var DefaultBootConfig = BootConfig{}
DefaultBootConfig provides sensible defaults for booting a lix web app. Copy this and override fields as needed.
var Flash = flashMessages{}
FlashMessages provides flash message helpers. Use with Render options: r.Render(200, page, Flash.Success("Saved!"))
Functions ¶
func Boot ¶
func Boot(cfg BootConfig) *echo.Echo
Boot creates an Echo server with the provided configuration. This is the main entry point for starting a lix web application.
func MakeErrorHandler ¶
func MakeErrorHandler(a *assets.Assets, notFound, internalError templ.Component, other func(code int) templ.Component) echo.HTTPErrorHandler
MakeErrorHandler creates an echo.HTTPErrorHandler that renders HTML error pages. For 404 errors, it renders notFound. For 500 errors, it renders internalError. For all other error codes, it calls other(code) to get the component to render. If a component is nil, it falls back to Echo's default error handler. Non-HTML requests (based on Accept header) also use the default handler.
func Parse ¶
Parse extracts form parameters from an HTTP request into a nested map. Handles bracket notation (user[name]) and dot notation (user.name). Single values are stored as string, multiple values as []string.
func ParseJSON ¶
ParseJSON reads a JSON request body into a nested map. Returns error if body is nil or not valid JSON. The body is consumed and cannot be read again.
Example:
params, err := web.ParseJSON(r) cs := changeset.Cast(&user, params, "name", "email")
func SendValidationResponse ¶
func SendValidationResponse[T any](w http.ResponseWriter, r *http.Request, cs *changeset.Changeset[T]) error
SendValidationResponse sends an SSE response with validation state. It builds an error map from the changeset using ShowError to determine which errors should be displayed.
Types ¶
type BootConfig ¶
type BootConfig struct {
// Assets provides asset management (fingerprinting, serving). Required.
Assets *assets.Assets
// Flash provides flash message storage. Optional.
// Create with NewFlashStore(secret) for session-based flash messages.
Flash *FlashStore
// SecureCookies sets whether cookies require HTTPS.
// Set to true in production, false for local development.
// Applies to Flash cookies when Flash is provided.
SecureCookies bool
// Registrars are route registrars (routes.Routes, routes.Imperative, etc.)
Registrars []Registrar
// HTTPErrorHandler handles HTTP errors. Use MakeErrorHandler to create one
// with templ components, or provide a fully custom handler.
HTTPErrorHandler echo.HTTPErrorHandler
}
BootConfig configures the web server created by Boot.
type FlashStore ¶
type FlashStore struct {
// contains filtered or unexported fields
}
FlashStore provides flash message storage using gorilla/sessions. Flash messages are stored in a session cookie and automatically cleared when retrieved, making them ideal for post-redirect feedback messages.
func NewFlashStore ¶
func NewFlashStore(secret []byte) *FlashStore
NewFlashStore creates a new FlashStore with the given secret. The secret should be a random 32-64 byte key for signing cookies. By default, cookies are not marked Secure (works on HTTP for development). Use SetSecure(true) for production HTTPS environments.
func (*FlashStore) Get ¶
func (f *FlashStore) Get(w http.ResponseWriter, r *http.Request) map[string][]string
Get retrieves all flash messages grouped by level and clears them. Messages are returned as a map where keys are levels and values are slices of messages. The session is saved to clear the flashes.
func (*FlashStore) Set ¶
func (f *FlashStore) Set(w http.ResponseWriter, r *http.Request, level, message string) error
Set adds a flash message at the specified level. Level should be one of: "info", "success", "warning", "error". The message will persist across a redirect and be cleared when retrieved.
func (*FlashStore) SetSecure ¶
func (f *FlashStore) SetSecure(secure bool)
SetSecure configures whether cookies require HTTPS. Set to true in production (HTTPS), false for local development (HTTP).
type Req ¶
type Req struct {
// contains filtered or unexported fields
}
Req wraps an HTTP request with helpers for rendering responses. It is the unified interface for handlers and templates. It implements URLOptions interface.
func ReqFromContext ¶
ReqFromContext retrieves Req from context (for templates).
func (*Req) FlashError ¶
FlashError sets an error-level flash message.
func (*Req) FlashSuccess ¶
FlashSuccess sets a success-level flash message. Use before redirects: r.FlashSuccess("Saved!"); return r.Redirect(303, "/")
func (*Req) FlashWarning ¶
FlashWarning sets a warning-level flash message.
func (*Req) Flashes ¶
Flashes retrieves all flash messages grouped by level. Messages are cleared after retrieval. Returns nil if no flash store is configured.
func (*Req) QueryParam ¶
QueryParam returns the query parameter value by name.
func (*Req) Response ¶
func (r *Req) Response() http.ResponseWriter
Response returns the http.ResponseWriter. Returns Echo's Response which properly handles headers for cookies/redirects.
type URLOptions ¶
URLOptions provides base URL components for full URL building. Implemented by *Req.
type ValidationResponse ¶
type ValidationResponse struct {
// Errors maps field names to their error messages.
Errors map[string]string `json:"errors"`
// Valid indicates whether the changeset passed validation.
Valid bool `json:"valid"`
}
ValidationResponse holds the SSE response data for form validation. This is sent back to the client to update the form's error state.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package form provides form helpers for template rendering with changeset integration.
|
Package form provides form helpers for template rendering with changeset integration. |
|
Package templhelpers provides helper functions for use in templ templates.
|
Package templhelpers provides helper functions for use in templ templates. |