Web & UI/Forms, Validation & File Uploads
Forms, Validation & File Uploads
Typed form binding, trimming, FormErrors auto-422 handling, recursive embedded inputs, and multipart uploads.
On this page
- Page and form route helpers
- Input struct binding tags
- Trimming whitespace with ,trim
- Blank HTML inputs and checkboxes
- Validation with router.FormErrors
- Lifecycle and auto-422 behavior
- Handler and Crest template example
- Recursive embedded input structs
- Multipart file uploads
- Controlling the upload size limit
- Complete upload handler with storage.Store
Fletch binds path parameters, query parameters, URL-encoded forms, JSON bodies, and multipart file uploads directly into typed Go structs. Handlers receive validated inputs and return a *router.PageResult instead of manually parsing r.FormValue or writing HTTP headers by hand.
Page and form route helpers
Register HTML page and form handlers with the typed helpers in github.com/fletchhq/fletch/router:
| Helper | HTTP Method |
|---|---|
router.GetPage(r, name, pattern, h) |
GET |
router.PostForm(r, name, pattern, h) |
POST |
router.PutForm(r, name, pattern, h) |
PUT |
router.PatchForm(r, name, pattern, h) |
PATCH |
router.DeleteForm(r, name, pattern, h) |
DELETE |
name is the route name used by URL helpers and fletch routes (it may be ""). Each handler has the signature func(c *router.Ctx, in *Input) (*router.PageResult, error), where Input is your input struct; call c.Context() for the request context.
func (m *Module) routes(a *fletch.App) {
r := a.Router()
router.GetPage(r, "signup.show", "/signup", m.showSignup)
router.PostForm(r, "signup.create", "/signup", m.signup)
}
Build responses with the PageResult helpers:
// Render a Crest component (200 OK by default)
return router.Page(views.Index{Items: items}), nil
// Redirect after a successful POST (303 See Other)
return router.SeeOther("/tasks"), nil
// Redirect with an explicit 3xx status
return router.Redirect("/login", http.StatusFound), nil
// Override status code or add response headers
return router.Page(views.Detail{Item: item}).
WithStatus(http.StatusCreated).
WithHeader("X-Task-ID", id), nil
// Return nil *router.PageResult with nil error for 204 No Content
return nil, nil
Input struct binding tags
Declare where each field comes from using struct tags:
| Tag | Source |
|---|---|
path:"id" |
URL route parameter (/tasks/{id}) |
query:"page" |
URL query string (?page=2) |
form:"title" |
application/x-www-form-urlencoded or multipart/form-data field |
validate:"..." |
Validation rules checked after binding: required, omitempty, min=N, max=N, and oneof=a b. Check anything else, such as email format, in the handler with AddError. |
When an input struct has no form tag on any field, the binder decodes JSON request bodies instead of form data.
Trimming whitespace with ,trim
Add ,trim to query or form tags on string fields to strip leading and trailing whitespace before validation runs:
type CreateProjectInput struct {
fletch.Public
router.FormErrors
Name string `form:"name,trim" validate:"required"`
Slug string `form:"slug,trim" validate:"required"`
}
The ,trim option is valid on string fields only. Putting ,trim on a non-string field or writing an unknown tag option fails when the binder is built rather than failing silently at request time.
Blank HTML inputs and checkboxes
HTML forms submit empty strings for unfilled text inputs and omit unchecked checkboxes entirely. The Fletch binder accounts for both behaviors:
- Blank values (
"") leave non-string scalar fields (such asint,float64,bool, ortime.Time) at their zero or default value without triggering a parse error. - Blank values in non-string slices (such as
[]int) are skipped instead of failing slice binding. boolfields take the last submitted value for that field name. This supports the standard hidden-input fallback for checkboxes:
<input type="hidden" name="active" value="false" />
<input type="checkbox" name="active" value="true" checked={active} />
When the checkbox is unchecked, the browser sends active=false. When checked, the browser sends active=false followed by active=true, and the binder sets the field to true.
Boolean parsing uses router.ParseBool(s string) (bool, error), which is case-insensitive and accepts:
- Truthy:
1,t,true,on,yes - Falsy:
"",0,f,false,off,no
Any other string returns a parse error.
Validation with router.FormErrors
For HTML forms, users expect to stay on the page with their input preserved and field errors highlighted next to the inputs. Embed router.FormErrors in the input struct to enable this flow:
type SignupInput struct {
fletch.Public
router.FormErrors
Email string `form:"email,trim" validate:"required"`
Name string `form:"name,trim" validate:"required"`
}
router.FormErrors provides four methods:
| Method | Behavior |
|---|---|
Valid() bool |
Returns true when no binding, validation, or custom errors have been recorded. |
Errors() []*BindError |
Returns all recorded field errors in order. |
FieldError(field string) string |
Returns the error message for a given field name, or "" if none. |
AddError(field, msg string) |
Records an application-level error inside the handler (for example a duplicate email check). |
Lifecycle and auto-422 behavior
When router.FormErrors is embedded:
- Binding and validation errors are collected onto
in.FormErrorsinstead of short-circuiting the request. Authorizestill runs before the handler, preventing unauthenticated callers from probing validation rules on protected forms.- Your handler runs with
in.Valid() == falseand the user’s submitted values still populated onin. - If the handler returns
router.Page(...)(body set, noLocationheader, and no explicitStatusset withWithStatus) while!in.Valid(), the router automatically sets status422 Unprocessable Entityand headerCache-Control: no-store.
Error collection also differs depending on whether FormErrors is embedded. BindStruct collects all field errors when FormErrors is embedded. Generated Bind code stops at the first error unless FormErrors is embedded, in which case it collects every failing field so the template can show all messages at once.
Handler and Crest template example
func (m *Module) signup(c *router.Ctx, in *SignupInput) (*router.PageResult, error) {
ctx := c.Context()
if in.Valid() {
exists, err := m.users.EmailExists(ctx, in.Email)
if err != nil {
return nil, err
}
if exists {
in.AddError("email", "An account with this email already exists.")
}
}
if !in.Valid() {
return router.Page(views.Signup{
Email: in.Email,
Name: in.Name,
Errors: in.FormErrors,
}), nil
}
if err := m.users.Register(ctx, in.Email, in.Name); err != nil {
return nil, err
}
return router.SeeOther("/welcome"), nil
}
The view props live in views/signup.go:
package views
import (
"github.com/fletchhq/fletch/router"
_ "myapp/ui/layouts"
)
type Signup struct {
Email string
Name string
Errors router.FormErrors
}
Render the field errors in views/signup.crest. The receiver is s, from Signup, and Crest if takes a plain condition with no initializer statement:
<layouts.App title="Sign up">
<form method="post" action="/signup">
<f:csrf />
<div>
<label for="name">Name</label>
<input id="name" name="name" type="text" value={s.Name} />
{if s.Errors.FieldError("name") != ""}
<p class="field-error">{s.Errors.FieldError("name")}</p>
{/if}
</div>
<div>
<label for="email">Email</label>
<input id="email" name="email" type="email" value={s.Email} />
{if s.Errors.FieldError("email") != ""}
<p class="field-error">{s.Errors.FieldError("email")}</p>
{/if}
</div>
<button type="submit">Create account</button>
</form>
</layouts.App>
<f:csrf /> works only after you register csrf.Element() in fletch.plugins.go and install the fletch.CSRF middleware; a new app has neither. See Security.
Because in.AddError("email", ...) flips in.Valid() to false, returning router.Page(...) triggers the same automatic 422 Unprocessable Entity status and Cache-Control: no-store header as a tag validation failure.
Recursive embedded input structs
The binder inspects input structs recursively via boundFields, promoting tagged fields from embedded structs according to reflect.VisibleFields rules. When an outer struct and a deeper embedded struct declare the same tag name, the outer field shadows the deeper one.
This lets you compose shared pagination, filtering, or authorization mixins across routes:
type PageParams struct {
Page int `query:"page"`
PerPage int `query:"per_page"`
Sort string `query:"sort,trim"`
}
type SearchInvoicesInput struct {
RequireBillingRole
PageParams
Status string `query:"status,trim"`
Sort string `query:"sort,trim" validate:"oneof=created_at amount"` // shadows PageParams.Sort
}
Multipart file uploads
Set enctype="multipart/form-data" on any <form> that uploads files, and bind fields to *multipart.FileHeader (single file) or []*multipart.FileHeader (multiple files) with a form:"..." tag. This template is views/avatar_form.crest, whose AvatarForm props (with an Errors router.FormErrors field) give the receiver a:
<form method="post" action="/profile/avatar" enctype="multipart/form-data">
<f:csrf />
<input type="file" name="avatar" accept="image/png,image/jpeg,image/webp" />
{if a.Errors.FieldError("avatar") != ""}
<p class="field-error">{a.Errors.FieldError("avatar")}</p>
{/if}
<button type="submit">Upload avatar</button>
</form>
Controlling the upload size limit
The default form body limit is 1 MiB. To raise or lower the limit for a route, implement router.FormLimiter on the input struct:
type FormLimiter interface {
MaxFormBytes() int64
}
When an input implements router.FormLimiter, the binder calls c.ParseFormLimit(in.MaxFormBytes()) before reading the request body. The limit covers the whole request body, including the other fields and the multipart boundaries and part headers, so set it above the largest file you accept and check the file size separately.
The fletch.CSRF middleware runs before the binder. When the token arrives in the _csrf form field, CSRF parses the multipart body itself, capped at 1 MiB by default, and answers 413 for anything larger, so a 5 MiB upload never reaches MaxFormBytes. Raise the CSRF cap to your largest upload route’s limit, here maxAvatarRequestBytes from the handler below (or send the token in the X-CSRF-Token header instead):
csrf, err := fletch.CSRF(secret, auth.WithCSRFMaxBodyBytes(maxAvatarRequestBytes))
if err != nil {
return nil, err
}
r.Use(csrf)
For multipart forms, this cap replaces the route’s limit, because the handler sees the form CSRF already parsed. Keep the per-field size checks in the handler.
Complete upload handler with storage.Store
Always verify the file size, sniff the actual content type from the file bytes instead of trusting the client header, validate the destination key with storage.ValidateKey, and write the file through storage.Store. RequireUser stands for your app’s own authorization mixin, which implements Authorize and exposes the signed-in user’s ID:
package profile
import (
"fmt"
"io"
"mime/multipart"
"net/http"
"path/filepath"
"github.com/fletchhq/fletch/router"
"github.com/fletchhq/fletch/storage"
"myapp/modules/profile/views"
)
const maxAvatarBytes = 5 << 20 // 5 MiB
// The request limit leaves room for the other fields and multipart framing.
const maxAvatarRequestBytes = maxAvatarBytes + 1<<20
type UploadAvatarInput struct {
RequireUser
router.FormErrors
Avatar *multipart.FileHeader `form:"avatar"`
}
func (*UploadAvatarInput) MaxFormBytes() int64 {
return maxAvatarRequestBytes
}
func (m *Module) uploadAvatar(c *router.Ctx, in *UploadAvatarInput) (*router.PageResult, error) {
if in.Avatar == nil {
in.AddError("avatar", "Choose an image file to upload.")
} else if in.Avatar.Size > maxAvatarBytes {
in.AddError("avatar", "Avatar must be 5 MiB or smaller.")
}
if !in.Valid() {
return router.Page(views.AvatarForm{Errors: in.FormErrors}), nil
}
f, err := in.Avatar.Open()
if err != nil {
return nil, err
}
defer f.Close()
var head [512]byte
n, err := io.ReadFull(f, head[:])
if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
return nil, err
}
mimeType := http.DetectContentType(head[:n])
var ext string
switch mimeType {
case "image/png":
ext = ".png"
case "image/jpeg":
ext = ".jpg"
case "image/webp":
ext = ".webp"
default:
in.AddError("avatar", "Avatar must be a PNG, JPEG, or WebP image.")
return router.Page(views.AvatarForm{Errors: in.FormErrors}), nil
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
return nil, err
}
key := filepath.ToSlash(fmt.Sprintf("avatars/%s%s", in.UserID(), ext))
if _, err := storage.ValidateKey(key); err != nil {
return nil, err
}
if _, err := storage.PutWithOptions(c.Context(), m.store, key, f, storage.PutOptions{ContentType: mimeType}); err != nil {
return nil, err
}
return router.SeeOther("/profile"), nil
}
For multiple files in one field (<input type="file" name="attachments" multiple />), declare Attachments []*multipart.FileHeader `form:"attachments"` on the input struct and validate each header in a loop.