web

package
v0.0.0-...-4778944 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2026 License: MIT Imports: 14 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
var DefaultBootConfig = BootConfig{}

DefaultBootConfig provides sensible defaults for booting a lix web app. Copy this and override fields as needed.

View Source
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

func Parse(r *http.Request) (map[string]any, error)

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

func ParseJSON(r *http.Request) (map[string]any, error)

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.

func SetReq

func SetReq(ctx context.Context, r *Req) context.Context

SetReq stores Req in context (called by Boot middleware).

func Static

func Static(e *echo.Echo, prefix string, fs http.FileSystem)

Static serves static files from the given filesystem.

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 Option

type Option func(*Req)

Option configures the response.

type Registrar

type Registrar interface {
	Register(*echo.Echo)
}

Registrar registers routes with Echo. Implemented by rb.Routes and rb.Func.

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 NewReq

func NewReq(c echo.Context, a *assets.Assets, f *FlashStore) *Req

NewReq creates a new Req from an echo.Context with optional assets and flash store.

func ReqFromContext

func ReqFromContext(ctx context.Context) *Req

ReqFromContext retrieves Req from context (for templates).

func (*Req) AssetPath

func (r *Req) AssetPath(logical string) string

AssetPath returns the fingerprinted URL for an asset.

func (*Req) Assets

func (r *Req) Assets() *assets.Assets

Assets returns the asset manager.

func (*Req) Bind

func (r *Req) Bind(i interface{}) error

Bind binds the request body to the given struct.

func (*Req) Context

func (r *Req) Context() context.Context

Context returns the request context.

func (*Req) Echo

func (r *Req) Echo() echo.Context

Echo returns the underlying echo.Context for advanced use cases.

func (*Req) FlashError

func (r *Req) FlashError(msg string)

FlashError sets an error-level flash message.

func (*Req) FlashInfo

func (r *Req) FlashInfo(msg string)

FlashInfo sets an info-level flash message.

func (*Req) FlashSuccess

func (r *Req) FlashSuccess(msg string)

FlashSuccess sets a success-level flash message. Use before redirects: r.FlashSuccess("Saved!"); return r.Redirect(303, "/")

func (*Req) FlashWarning

func (r *Req) FlashWarning(msg string)

FlashWarning sets a warning-level flash message.

func (*Req) Flashes

func (r *Req) Flashes() map[string][]string

Flashes retrieves all flash messages grouped by level. Messages are cleared after retrieval. Returns nil if no flash store is configured.

func (*Req) FormValue

func (r *Req) FormValue(name string) string

FormValue returns the form value by name.

func (*Req) HTML

func (r *Req) HTML(code int, html string) error

HTML sends an HTML string response.

func (*Req) Host

func (r *Req) Host() string

Host returns the request host.

func (*Req) JSON

func (r *Req) JSON(code int, i interface{}) error

JSON sends a JSON response.

func (*Req) NoContent

func (r *Req) NoContent(code int) error

NoContent sends a response with no body.

func (*Req) Param

func (r *Req) Param(name string) string

Param returns the path parameter value by name.

func (*Req) QueryParam

func (r *Req) QueryParam(name string) string

QueryParam returns the query parameter value by name.

func (*Req) Redirect

func (r *Req) Redirect(status int, url string) error

Redirect redirects to the given URL.

func (*Req) Render

func (r *Req) Render(status int, component templ.Component, opts ...Option) error

Render renders a templ component as an HTML response.

func (*Req) Request

func (r *Req) Request() *http.Request

Request returns the underlying *http.Request.

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.

func (*Req) Scheme

func (r *Req) Scheme() string

Scheme returns the request scheme (http or https).

func (*Req) Stream

func (r *Req) Stream(code int, contentType string, reader io.Reader) error

Stream sends a streaming response.

func (*Req) String

func (r *Req) String(status int, s string) error

String returns a string response.

type URLOptions

type URLOptions interface {
	Scheme() string
	Host() string
}

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.

Jump to

Keyboard shortcuts

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