Help us shape the future of Go! Take the 2026 Go Developer Survey

web

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Overview

Package web provides a Gin engine with the security middleware C4Stack apps share: request IDs and logging, safe panic recovery, a host check, security headers with an extensible Content Security Policy, body limits and CSRF protection. It also serves an http.Handler with health endpoints and graceful shutdown.

The app owns the engine New returns. It adds its own routes and middleware, and decides which route groups need CSRF checks.

Index

Constants

View Source
const (
	CSRFField  = "csrf_token"
	CSRFHeader = "X-CSRF-Token"
)

CSRFField is the form field that carries the CSRF token. HTMX and scripts can send the token in the CSRFHeader header instead.

View Source
const DefaultMaxBodyBytes = 1 << 20

DefaultMaxBodyBytes is the request body limit when Config.MaxBodyBytes is zero.

Variables

View Source
var ErrNoCookie = errors.New("web: no valid sealed cookie")

ErrNoCookie is returned by SealedCookie when the cookie is missing, expired or was not sealed by this app.

Functions

func AllowCSP

func AllowCSP(extra CSP) gin.HandlerFunc

AllowCSP adds sources to the Content Security Policy of the routes it is applied to. Modules use it on the groups they mount, for example to let a login page reach its identity provider.

func CSRF

func CSRF(c *gin.Context)

CSRF rejects state-changing requests that lack a valid CSRF token or come from another origin. Use it on public routes with forms; accounts.RequireSignIn already includes it. API-key routes and webhooks must not use it.

Other middleware can call CSRF directly and check c.IsAborted afterwards. A rejected request gets only a status, not yet written, so middleware that runs before CSRF can render an error page after c.Next.

func CSRFToken

func CSRFToken(c *gin.Context) string

CSRFToken returns the token that forms on this page must submit.

func ClearSealedCookie

func ClearSealedCookie(c *gin.Context, name string)

ClearSealedCookie deletes a cookie set by SetSealedCookie.

func Log

func Log(c *gin.Context) *slog.Logger

Log returns the request's logger, which carries its request ID.

func MaxBody

func MaxBody(n int64) gin.HandlerFunc

MaxBody sets the request body limit for the routes it is applied to.

func New

func New(cfg Config) (*gin.Engine, error)

New returns a Gin engine with C4Stack's security middleware installed.

func SealedCookie

func SealedCookie(c *gin.Context, name string) ([]byte, error)

SealedCookie returns the value stored by SetSealedCookie.

func Serve

func Serve(ctx context.Context, s Server, ready func(context.Context) error) error

Serve runs s until ctx is cancelled, then shuts down gracefully: readiness fails first, the listener stays open for DrainDelay, and in-flight requests get ShutdownTimeout to finish. ready reports whether the app can take traffic.

func SetSealedCookie

func SetSealedCookie(c *gin.Context, name string, value []byte, maxAge time.Duration)

SetSealedCookie stores value in an encrypted, authenticated cookie that expires after maxAge. Use it for short-lived server state, not for large data: browsers limit cookies to about 4 KB.

func URL

func URL(c *gin.Context, path string) string

URL returns the absolute URL of path on the app's public origin.

Types

type CSP

type CSP struct {
	Scripts     []string // script-src
	Styles      []string // style-src
	Images      []string // img-src
	Fonts       []string // font-src
	Connect     []string // connect-src
	Frames      []string // frame-src
	FormActions []string // form-action
}

CSP lists Content Security Policy sources. Each field adds sources to one directive of the default policy, which allows only the app's own origin.

func (CSP) String

func (p CSP) String() string

String renders the policy as a Content-Security-Policy header value.

type Config

type Config struct {
	// PublicURL is the canonical origin users reach the app on, such as
	// https://acme.example. Plain HTTP is accepted only for loopback hosts.
	PublicURL string
	// Origins lists further origins the app is served on, such as a second hostname.
	// Requests may address their hosts, and forms may post from them. Each must use
	// PublicURL's scheme. URL keeps using PublicURL.
	Origins []string
	// AnyHost accepts requests addressed to any host, for development behind a proxy
	// or tunnel whose hostname the app cannot know. Forms still post only from
	// PublicURL and Origins. Leave it off in production.
	AnyHost bool
	// SecretKey signs CSRF tokens and seals cookies. It must be at least 32 bytes and
	// the same on every replica.
	SecretKey string
	// CSP lists sources added to the default Content Security Policy on every route.
	CSP CSP
	// MaxBodyBytes limits request bodies. Zero means DefaultMaxBodyBytes.
	MaxBodyBytes int64
	// TrustedProxies lists the proxies whose forwarding headers set the client IP.
	// None are trusted by default.
	TrustedProxies []string
	// Logger receives request logs. Zero means slog.Default().
	Logger *slog.Logger
}

Config configures the engine New returns.

type Server

type Server struct {
	// Addr is the listen address, such as ":8080".
	Addr    string
	Handler http.Handler
	// HealthPath serves HealthPath+"/live" and HealthPath+"/ready" in front of Handler,
	// so probes skip the host check and the request log. Empty disables them.
	HealthPath string
	// DrainDelay is how long readiness fails before the listener stops accepting
	// requests, so load balancers stop routing first. Zero means 5 seconds.
	DrainDelay time.Duration
	// ShutdownTimeout bounds how long in-flight requests get to finish. Zero means
	// 30 seconds.
	ShutdownTimeout time.Duration
	// Logger receives startup and shutdown messages. Zero means slog.Default().
	Logger *slog.Logger
}

Server describes how Serve runs an http.Handler.

Jump to

Keyboard shortcuts

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