web

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 68 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package web provides the core HTTP types shared across Laravel: Request, Response, Handler, Middleware, Kernel, and Error.

A Handler receives a *Request and returns a *Response. Pass errors to Fail to render the appropriate HTTP error response:

func Show(r *web.Request) *web.Response {
	user, err := find(r, r.PathValue("user"))
	if err != nil {
		return web.Fail(err)
	}

	return web.JSON(user)
}

Request embeds *http.Request and implements context.Context, so you can pass r directly to database queries, HTTP clients, and other context-aware calls. Response is a mutable value until the Kernel writes it, allowing middleware to inspect or modify its status, headers, and cookies after the handler returns.

Index

Constants

View Source
const NoLimit = -1

NoLimit disables a limit in Limits, such as for a route that streams its own request body.

View Source
const RequestIDHeader = "X-Request-Id"

RequestIDHeader is the HTTP header used to read an incoming request ID and return the active request ID on responses.

Variables

View Source
var ErrNoView = errors.New("web: the request rendered no view")

ErrNoView is returned by Request.Rerender when the request did not render a view.

View Source
var ErrShutdown = errors.New("web: the server shut down while the request was in progress")

ErrShutdown is the context cancellation cause used when the server's graceful shutdown deadline expires while a request or background task is still running.

Functions

func Capture

func Capture(hr *http.Request, into *Captured, plainCookies ...string) *http.Request

Capture returns a shallow copy of hr that instructs Kernel.ServeHTTP to populate into with the processed *Request, error cause, and reported errors for test assertions. Cookie names listed in plainCookies bypass decryption in go.laravel.com/middleware.EncryptCookies.

func Errorf

func Errorf(status int, format string, args ...any) error

Errorf returns an *Error with status and a formatted visitor-facing message, for code below the handler that returns an error rather than a *Response:

if ticket.Status == models.StatusResolved {
	return web.Errorf(http.StatusConflict, "Ticket #%d is already resolved.", ticket.ID)
}

Pass the returned error to Fail (directly or wrapped) to send that status and message. Wrapping an error with %w sets Error.Err, causing 5xx errors to be reported as faults.

func LogHandler

func LogHandler(inner slog.Handler) slog.Handler

LogHandler wraps inner so every log record automatically includes context attributes: the active trace and span IDs when tracing is enabled, the request ID from RequestID, the active command, job, or scheduled task metadata, and shared log context values. When tracing is enabled and ctx carries a recording span, LogHandler also attaches each log record as a span event:

slog.InfoContext(r, "Order placed.", "order", order.ID)

Context attributes are always placed at the top level of the record, even when inner has nested groups via WithGroup.

func PublicMessage

func PublicMessage(r *Request, err error) string

PublicMessage returns the visitor-facing message for err: the message from the error in err's chain that chose its HTTP status, stripping outer wrapping context (so a 404 wrapped with "loading post 7: %w" yields "Not Found").

Outside debug mode, internal details stay hidden: a server error returns "Server Error", and sql.ErrNoRows returns "Not Found". A server error you chose for the visitor, an *Error without a cause such as one from Abort or Abortf, still returns its message. In debug mode, unannotated server errors return err.Error().

JSON error responses show this message. HTML error pages show the status's reason phrase, such as "Not Found", except a 403's page, which shows this message.

func RequestID

func RequestID(ctx context.Context) string

RequestID returns the request ID carried by ctx, or "" if ctx is not associated with an HTTP request.

func StatusOf

func StatusOf(err error) int

StatusOf returns the HTTP status code that err renders with, defaulting to http.StatusInternalServerError (500) when no error in err's chain sets a 4xx or 5xx status.

Types

type Captured

type Captured struct {
	// Request is the [*Request] observed by the application, including its
	// matched route and session.
	Request *Request
	// Cause is the error that produced the response, or nil.
	Cause error
	// Reported holds all errors reported during the request, in order.
	Reported []error
	// contains filtered or unexported fields
}

Captured holds request and error state recorded by Kernel.ServeHTTP for a request tagged with Capture.

type Error

type Error struct {
	// Status is the HTTP status code for the rendered response.
	Status int
	// Message is the visitor-facing message. When empty, the standard HTTP
	// status text (such as "Not Found") is used.
	Message string
	// Header holds additional headers merged onto the rendered error response.
	Header http.Header
	// Err is the underlying cause. It is logged and reported for 5xx errors
	// but never shown to visitors outside debug mode.
	Err error
}

Error is an error carrying an HTTP status code, an optional visitor-facing message, optional response headers, and an optional underlying cause:

return &web.Error{Status: http.StatusNotFound}

Handlers can return a status directly with Abort or Abortf. Any custom error type can also choose its HTTP status by implementing StatusCode() int and attach response headers by implementing Header() http.Header. Errors without an HTTP status render as 500 Internal Server Error.

func (*Error) Error

func (e *Error) Error() string

Error returns e.Message, or the status text combined with e.Err (such as "Bad Gateway: dial tcp: connection refused") when Message is empty. Visitors see only Message or the standard status text.

func (*Error) StatusCode

func (e *Error) StatusCode() int

StatusCode returns e.Status.

func (*Error) TraceSummary

func (e *Error) TraceSummary() (string, string)

TraceSummary describes an error without a cause by its status. One with a cause is described by its cause.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying cause e.Err.

type ErrorPage

type ErrorPage struct {
	// Status is the HTTP status code, such as 404.
	Status int
	// Title is the status's reason phrase, such as "Not Found".
	Title string
	// Message is what the page shows: the status's reason phrase, such as
	// "Not Found", or for a 403 the error's message, such as a policy's
	// denial.
	Message string
}

ErrorPage is the template data passed to custom error views (errors.<status>, errors.4xx, or errors.5xx).

type Errors

type Errors struct {
	// Ignore returns true for server errors that should not be logged or
	// reported. Client errors (4xx), [*Error] values without a cause, and
	// client-disconnect errors are already skipped.
	Ignore func(err error) bool
	// Report runs after a server error is logged, allowing you to forward
	// errors to an external tracker. During HTTP requests, ctx is the
	// [*Request].
	Report func(ctx context.Context, err error)
	// Render returns a custom [*Response] for err, or nil to use default
	// rendering. If the returned response fails to finish, default rendering
	// is used instead.
	Render func(r *Request, err error) *Response
	// Respond intercepts every rendered error response (including defaults)
	// and returns the final [*Response] to send. If the returned response is
	// nil or fails to finish, res is sent unchanged.
	Respond func(r *Request, res *Response, err error) *Response
	// DontFlash lists input field dot paths (such as "ssn", "card.number", or
	// "cards.*.number") excluded from flashed old input on validation redirects
	// and [Response.WithInput]. Password fields (password,
	// password_confirmation, current_password) at any depth are always excluded.
	DontFlash []string
}

Errors configures how an application ignores, reports, and renders errors. Every field is optional.

type Event

type Event struct {
	// Name sets the SSE event type. When empty, defaults to "update".
	Name string
	// Data is the event payload. Strings and []byte are written verbatim,
	// [Partial] values render as HTML using the request's view helpers, and
	// all other values are marshaled as JSON.
	Data any
	// ID sets the SSE id field, which browsers send back in Last-Event-ID on
	// reconnect.
	ID string
}

Event represents a single server-sent event (SSE) message.

type EventStream

type EventStream struct {
	// Events yields the events to stream after the handler returns. Producers
	// should stop when the request context is canceled.
	Events iter.Seq[Event]
	// Stream produces events by calling send and may return an error. When set,
	// Stream is used instead of Events. Returning an error other than a client
	// disconnect reports the error and ends the stream without sending End.
	Stream func(send func(Event) error) error
	// KeepAlive sets how often an SSE comment is written during quiet periods
	// to keep proxy connections open. Zero defaults to 15 seconds.
	KeepAlive time.Duration
	// End overrides the final event sent when the stream finishes without
	// error. When nil, EventStream sends an "update" event with data
	// "</stream>" unless WithoutEndEvent is true.
	End *Event
	// WithoutEndEvent omits the final event when the stream finishes.
	WithoutEndEvent bool
}

EventStream configures a server-sent events (SSE) response. Use Events or StreamEvents when the default keep-alive interval and end event are sufficient.

func (EventStream) Response

func (s EventStream) Response() *Response

Response builds the server-sent events *Response for s.

type Handler

type Handler func(r *Request) *Response

Handler processes an HTTP request and returns a *Response. Return Fail or Abort to respond with an error; see Error for status code resolution.

func WrapHandler

func WrapHandler(handler http.Handler) Handler

WrapHandler adapts a standard http.Handler into a Handler. The wrapped handler writes directly to the response writer after middleware returns, so middleware can add headers and cookies to the response but cannot inspect its status code or body.

To mount a standard handler without automatic request body parsing, register it with go.laravel.com/routing.Router.Handle rather than a verb method such as Post.

func (Handler) Respond

func (h Handler) Respond(r *Request) (res *Response)

Respond executes h and returns its finished *Response. Any Fail response or panic is rendered as an error response and reported when it is a server error. A nil return value becomes a 204 No Content response.

func (Handler) Through

func (h Handler) Through(middleware ...Middleware) Handler

Through wraps h in middleware, with the first element running outermost.

func (Handler) Within

func (h Handler) Within(timeout time.Duration, cause error) Handler

Within returns a Handler that cancels the request context with cause and responds with 503 Service Unavailable if h exceeds timeout or is still running at the server's shutdown deadline.

Within executes h against an isolated copy of the request state and commits that state back only if h finishes in time. A handler that outlives the deadline cannot mutate the session, input, or cookies of the 503 response.

type InputError

type InputError struct {
	// Fields lists the invalid fields and their error messages in declaration
	// order.
	Fields validation.Errors
	// Bag names the error bag for pages with multiple forms. Empty uses the
	// bag that the request's [Request.ValidateIn] chose, or else the form's
	// _form input, or else the default bag.
	Bag string
}

InputError reports validation or type-binding failures on request input. JSON requests receive a 422 Unprocessable Entity payload listing each field's errors, while browser requests on routes with a session redirect back with flashed errors and old input.

func (*InputError) Error

func (e *InputError) Error() string

Error returns the first validation message followed by the count of remaining errors, such as "The title field is required. (and 2 more errors)".

func (*InputError) StatusCode

func (e *InputError) StatusCode() int

StatusCode returns http.StatusUnprocessableEntity (422).

type JSONStream

type JSONStream[T any] struct {
	// Items yields the array elements after the handler returns.
	Items iter.Seq2[T, error]
	// Key wraps the streamed array in a JSON object under this key, such as
	// {"users":[...]}. When empty, the array is written at the top level.
	Key string
}

JSONStream configures a streamed JSON array response. Use StreamJSON when you do not need to wrap the array under a JSON object key.

func (JSONStream[T]) Response

func (s JSONStream[T]) Response() *Response

Response builds a streamed JSON *Response for s.

type Kernel

type Kernel struct {
	// Config holds the application configuration. When nil, [config.Default]
	// is used.
	Config *config.Config
	// Handler handles incoming requests, typically the global middleware stack
	// wrapping the router.
	Handler Handler
	// Errors configures error ignoring, reporting, and custom rendering.
	Errors Errors
	// Head sets the default HTML head metadata for rendered pages.
	Head head.Config
	// Logger receives request logs and reported errors. When nil,
	// [slog.Default] is used.
	Logger *slog.Logger
	// Proxies lists reverse proxies trusted for X-Forwarded-* headers.
	Proxies Proxies
	// Health is the GET/HEAD path (such as "/up") answered with a 200 OK
	// health page without running Handler. Empty disables the health check.
	Health string
	// Views renders HTML templates for [View]. When nil, view rendering fails.
	Views Views
	// Public is the directory containing static files. Requests targeting a
	// directory inside Public preserve their trailing slash.
	Public string
	// Stop is closed when the server begins shutting down, terminating active
	// server-sent event streams.
	Stop <-chan struct{}
	// Tracer creates OpenTelemetry server spans for requests. When nil,
	// tracing is disabled.
	Tracer trace.Tracer
	// Background runs tasks scheduled with [Request.Background] and tracks
	// them for graceful shutdown. When nil, tasks run in untracked goroutines.
	Background func(ctx context.Context, work func(ctx context.Context))
	// Scope attaches the application scope to each incoming request's context
	// so framework packages can resolve services from the request. Package
	// laravel sets Scope automatically. When nil, Kernel attaches a minimal
	// scope exposing Config, Logger, Views, and Report.
	Scope func(r *Request) context.Context
}

Kernel is the outermost HTTP layer of a Laravel application. It implements http.Handler, wrapping each incoming *http.Request into a *Request, invoking Handler, and writing the returned *Response.

Around Handler, Kernel resolves client IP and scheme from trusted Proxies, trims trailing path slashes, assigns a request ID, recovers panics, renders and reports errors, and logs each completed request.

Package laravel constructs the application's Kernel automatically. Construct a Kernel directly when unit-testing a Handler or Middleware in isolation; the zero Kernel responds with 404 Not Found.

func (*Kernel) Report

func (k *Kernel) Report(ctx context.Context, err error, attrs ...any)

Report logs err and invokes Errors.Report when err is a fault (a 5xx error other than an *Error without a cause). Non-fault errors and nil are ignored. When ctx is a *Request, the log entry includes the request's method and path and test capture records err. Additional slog key-value pairs in attrs are appended to the log entry.

func (*Kernel) ServeHTTP

func (k *Kernel) ServeHTTP(w http.ResponseWriter, hr *http.Request)

ServeHTTP implements http.Handler, wrapping hr into a *Request, running k.Handler, writing the response, and running registered Request.OnFinish cleanup callbacks.

type Limits

type Limits struct {
	// Body is the maximum size in bytes for non-multipart request bodies and
	// for total text fields in multipart requests.
	Body int64
	// Uploads is the maximum total size in bytes for multipart request bodies,
	// including uploaded files.
	Uploads int64
	// Fields is the maximum number of fields allowed in a JSON body, form body,
	// or query string.
	Fields int
	// Files is the maximum number of uploaded files allowed in a multipart
	// request.
	Files int
}

Limits configures maximum sizes and counts accepted in a request body. Pass NoLimit (or any negative value) to disable a limit.

type Middleware

type Middleware interface {
	Handle(r *Request, next Next) *Response
}

Middleware wraps a Handler to inspect or modify requests and responses, or short-circuit execution without calling next.

func WrapMiddleware

func WrapMiddleware(middleware func(http.Handler) http.Handler) Middleware

WrapMiddleware adapts a standard net/http middleware function into a Middleware:

route.Middleware(web.WrapMiddleware(nosurf.NewPure))

For buffered responses, the wrapped middleware observes the inner status, headers, and body, and its output becomes the returned *Response. For streamed responses and files, the middleware can modify headers only.

The wrapped function pointer serves as the middleware's identity in a Stack, so passing WrapMiddleware with the same function removes, replaces, or excludes it.

type MiddlewareFunc

type MiddlewareFunc func(r *Request, next Next) *Response

MiddlewareFunc adapts a plain function into a Middleware.

func (MiddlewareFunc) Handle

func (f MiddlewareFunc) Handle(r *Request, next Next) *Response

Handle calls f(r, next).

type Next

type Next func(r *Request) *Response

Next invokes the next middleware or the route's Handler. It always returns a finished *Response, because handler errors and panics are already rendered into error responses before Next returns.

type PanicError

type PanicError struct {
	// Value is the argument passed to panic.
	Value any
	// Stack is the stack trace captured when the panic was recovered.
	Stack []byte
	// contains filtered or unexported fields
}

PanicError wraps a panic recovered by the Kernel from a handler, middleware, or background task, rendering as a 500 Internal Server Error.

func (*PanicError) Error

func (e *PanicError) Error() string

Error formats the recovered panic value as "panic: <value>".

func (*PanicError) Unwrap

func (e *PanicError) Unwrap() error

Unwrap returns e.Value if it implements error, or nil otherwise.

type Partial

type Partial struct {
	// View is the dot-separated view name, such as "posts.row".
	View string
	// Data is the template data passed to View.
	Data any
}

Partial identifies a view template and data to render as an HTML fragment, such as the payload of a server-sent Event.

type Proxies

type Proxies struct {
	// contains filtered or unexported fields
}

Proxies holds the set of reverse proxies trusted to supply client IP addresses, schemes, and hosts via X-Forwarded-* headers. The zero value trusts no proxies and strips forwarded headers from every incoming request.

func ParseProxies

func ParseProxies(proxies ...string) (Proxies, error)

ParseProxies parses IP addresses and CIDR networks (such as "10.0.0.0/8") into a Proxies trust list. Passing "*" trusts every proxy, which is appropriate only when your application sits exclusively behind a trusted load balancer. It returns an error if any entry is not a valid IP address, CIDR prefix, or "*".

type Request

type Request struct {
	*http.Request
	// contains filtered or unexported fields
}

Request represents an incoming HTTP request. It embeds *http.Request, exposing standard fields and methods such as Method, URL, Header, Context, and PathValue, while adding input parsing, content negotiation, session access, authentication lookup, and URL helpers.

Request also implements context.Context by delegating Deadline, Done, Err, and Value to r.Context(), so handlers can pass r directly to framework and database calls such as config.From(r) and slog.InfoContext(r, ...).

func NewRequest

func NewRequest(r *http.Request) *Request

NewRequest wraps r in a *Request backed by a default Kernel, useful when calling a Handler directly in unit tests. Requests served through an application are wrapped by its Kernel automatically.

func (*Request) Accepts

func (r *Request) Accepts(contentTypes ...string) bool

Accepts reports whether the request's Accept header permits any of contentTypes. Requests without an Accept header accept all content types.

func (*Request) Background

func (r *Request) Background(work func(ctx context.Context) error)

Background runs work in a separate goroutine so the HTTP response does not wait for it, such as notifying a webhook that an order shipped:

r.Background(func(ctx context.Context) error {
	return webhooks.OrderShipped(ctx, order.ID)
})

Inside a database transaction, work starts after the outermost transaction commits, and a rollback discards it. The context passed to work keeps the request's values (such as the request ID for logging) but drops its cancellation and database transaction so work continues after the response completes. Read any needed request input or uploads before calling Background, because the request body and temporary upload files are cleaned up once the handler returns.

Errors returned by work and recovered panics are passed to Request.Report. During graceful shutdown, the server waits for background work up to SERVER_SHUTDOWN_TIMEOUT before canceling its context with ErrShutdown. Because background work is not persisted or retried on process crash, use a queued job for work that must not be lost.

func (*Request) BearerToken

func (r *Request) BearerToken() string

BearerToken extracts the bearer token from the Authorization header, or returns "" if the header is missing or uses another scheme.

func (*Request) Bind

func (r *Request) Bind[T any]() (T, error)

Bind decodes the request's body input (JSON, URL-encoded form, or multipart fields and uploads) into a new value of type T. Struct fields match input keys by their json tag:

form, err := r.Bind[NewUser]()
if err != nil {
	return web.Fail(err)
}

Bind reads only the request body; to read query string parameters, use Request.Query. String fields (and pointers, validation.Sometimes, slices, arrays, or maps of strings) may carry a transform:"lowercase" or transform:"uppercase" tag to normalize casing during binding without altering the request's stored input. Missing fields keep their zero values. A value that does not fit its field type returns an *InputError, which renders a 422 response naming the field.

func (*Request) BindInto

func (r *Request) BindInto(dst any) error

BindInto decodes the request's body input into the struct pointed to by dst. BindInto panics if dst is not a non-nil pointer.

func (*Request) Cookie

func (r *Request) Cookie(name string) (*http.Cookie, error)

Cookie returns the incoming cookie named name, or http.ErrNoCookie. Values are percent-unescaped, and routes running go.laravel.com/middleware.EncryptCookies decrypt them automatically.

func (*Request) CookieValue

func (r *Request) CookieValue(name string) string

CookieValue returns the decoded value of the incoming cookie named name, or "" if the cookie is not present:

theme := cmp.Or(r.CookieValue("theme"), "light")

func (*Request) Cookies

func (r *Request) Cookies() []*http.Cookie

Cookies returns all incoming cookies with values decoded as described by Request.Cookie.

func (*Request) Deadline

func (r *Request) Deadline() (time.Time, bool)

Deadline delegates to r.Context().Deadline().

func (*Request) Done

func (r *Request) Done() <-chan struct{}

Done delegates to r.Context().Done().

func (*Request) Err

func (r *Request) Err() error

Err delegates to r.Context().Err().

func (*Request) ExpectsJSON

func (r *Request) ExpectsJSON() bool

ExpectsJSON reports whether the client expects a JSON response: the matched route forces JSON, Request.WantsJSON is true, or the request is an AJAX request that accepts any content type.

func (*Request) FullURL

func (r *Request) FullURL() string

FullURL returns the full request URL including its scheme, host, path, and query string.

func (*Request) FullURLWithQuery

func (r *Request) FullURLWithQuery(values url.Values) string

FullURLWithQuery returns the full request URL with values merged into its query string. Setting a key such as "tags" also replaces any existing bracketed keys like "tags[]" or "tags[0]".

func (*Request) FullURLWithoutQuery

func (r *Request) FullURLWithoutQuery(keys ...string) string

FullURLWithoutQuery returns the full request URL with each parameter in keys removed, including bracketed forms such as "tags[]" and "tags[0]".

func (*Request) HasSession

func (r *Request) HasSession() bool

HasSession reports whether a session.Session is attached to r.

func (*Request) HasValidSignature

func (r *Request) HasValidSignature() bool

HasValidSignature reports whether r.URL carries a valid, unexpired signature verified by urls.Verify.

func (*Request) Hostname

func (r *Request) Hostname() string

Hostname returns the request host without its port, such as "example.com".

func (*Request) ID

func (r *Request) ID() string

ID returns the request's unique ID, also sent in the RequestIDHeader response header and included on request log entries.

func (*Request) IP

func (r *Request) IP() string

IP returns the client's IP address, respecting X-Forwarded-For when the request comes through a trusted proxy.

func (*Request) Is

func (r *Request) Is(patterns ...string) bool

Is reports whether the request path matches any pattern in patterns, where "*" matches any sequence of characters including slashes (for example, r.Is("admin/*")).

func (*Request) IsAJAX

func (r *Request) IsAJAX() bool

IsAJAX reports whether the request carries the X-Requested-With: XMLHttpRequest header.

func (*Request) IsJSON

func (r *Request) IsJSON() bool

IsJSON reports whether the request Content-Type is JSON (application/json or any +json media type).

func (*Request) IsPrefetch

func (r *Request) IsPrefetch() bool

IsPrefetch reports whether the request is a browser prefetch (via X-Moz, Purpose, or Sec-Purpose headers).

func (*Request) IsSecure

func (r *Request) IsSecure() bool

IsSecure reports whether the request arrived over HTTPS, either directly or via a trusted proxy's X-Forwarded-Proto header.

func (*Request) JSON

func (r *Request) JSON[T any]() (T, error)

JSON unmarshals the request body as JSON into a new value of type T (such as a struct or slice) while leaving r.Body buffered and readable again. It returns a 400 *Error if the body is empty, unreadable, or malformed JSON.

func (*Request) JSONInto

func (r *Request) JSONInto(dst any) error

JSONInto unmarshals the request body as JSON into dst while leaving r.Body buffered and readable again.

func (*Request) Limits

func (r *Request) Limits() Limits

Limits returns the active body Limits for r.

func (*Request) OnFinish

func (r *Request) OnFinish(clean func())

OnFinish registers a cleanup callback to run after the HTTP response is flushed to the client. Callbacks run in registration order regardless of whether the request succeeded or failed, and are excluded from the logged request duration. The request context is canceled before callbacks run, and a callback registered after the response has already finished runs immediately.

func (*Request) Page

func (r *Request) Page(size int) pagination.Page

Page builds a pagination.Page with size items per page from the request's "page" and "cursor" query parameters, ready to pass to a query's Paginate or CursorPaginate method:

posts, err := model.Query[models.Post]().Latest("id").Paginate(r, r.Page(15))

Missing or invalid page numbers default to page 1, and an invalid cursor reads from the first page. Generated pagination links are rooted at Request.FullURL.

func (*Request) PageNamed

func (r *Request) PageNamed(name string, size int) pagination.Page

PageNamed builds a pagination.Page reading both the page number and cursor from the query parameter named name, allowing multiple independent paginated lists on the same page.

func (*Request) ParseInput

func (r *Request) ParseInput() error

ParseInput reads and parses the request body (JSON, URL-encoded form, or multipart form). The router calls ParseInput before running a route's handler so malformed or oversized bodies fail early. Calling ParseInput more than once returns the cached result.

On routes handled by a standard http.Handler, ParseInput leaves the body unread for the handler.

func (*Request) PathInt

func (r *Request) PathInt(name string) (int64, error)

PathInt parses the route path parameter named name as an int64. If the value is not a valid integer, it returns a 404 *Error suitable for passing directly to Fail.

func (*Request) PeekBody

func (r *Request) PeekBody(n int) ([]byte, error)

PeekBody returns up to the first n bytes of r.Body without consuming them from subsequent reads. Peeked bytes are buffered and counted against the request's active Limits when the body is later read rather than when peeked, allowing global middleware (such as go.laravel.com/middleware.SpoofMethods) to inspect the start of a body before routing applies route-specific limits.

If r.Body is nil, http.NoBody, or n is not positive, PeekBody leaves r.Body untouched and returns nil, nil.

func (*Request) Prefers

func (r *Request) Prefers(contentTypes ...string) string

Prefers returns the most preferred media type from contentTypes according to the request's Accept header, or "" if none match. A request with no Accept header returns contentTypes[0].

func (*Request) Query

func (r *Request) Query[T any]() (T, error)

Query binds and validates the request's query string parameters into a new value of type T, ignoring the request body. Struct fields match query keys by their json tag, and input transforms such as TrimStrings apply.

Query is lenient for optional fields: if an optional parameter doesn't fit its field type or fails a rule (such as a stale bookmark like ?page=abc or ?status=deleted), that top-level field stays at its zero value (or its starting value when using Request.QueryInto) instead of failing the request.

If a field is required (via go.laravel.com/validation/rule.Required or a conditional presence rule in Rules), any failure on that field returns a 400 Bad Request *Error wrapping *InputError. Passed to Fail, API clients receive a 400 JSON payload listing the errors, and browsers receive a 400 error page rather than a redirect.

filters, err := r.Query[ProductFilters]()
if err != nil {
	return web.Fail(err)
}

To supply non-zero fallback defaults (such as Page: 1), use Request.QueryInto with a pre-populated struct.

func (*Request) QueryInto

func (r *Request) QueryInto(dst any) error

QueryInto binds and validates the request's query string parameters into the struct pointed to by dst, ignoring the request body. Pre-populated field values on dst serve as defaults when a query parameter is missing, blank, or invalid on an optional field:

filters := ProductFilters{Page: 1}
if err := r.QueryInto(&filters); err != nil {
	return web.Fail(err)
}

If dst implements Authorize(r *web.Request) error, QueryInto calls it first. QueryInto panics if dst is not a non-nil pointer to a struct or if a rule names a field that the struct does not declare.

func (*Request) RenderedView

func (r *Request) RenderedView() (name string, data any, ok bool)

RenderedView returns the view name and template data passed to View during this request. It returns ok == false if the request did not render a view.

func (*Request) Report

func (r *Request) Report(err error)

Report logs err and invokes Errors.Report without failing the current request. Non-fault errors (such as 404 or an *Error without a cause) are ignored.

func (*Request) Rerender

func (r *Request) Rerender(name string, data any) ([]byte, error)

Rerender renders name with data using the same request context, session snapshot, and fragment list as the original view render. Tests use Rerender after a response completes to compare rendered HTML against expectations. It returns ErrNoView if the request did not render a view.

func (*Request) Root

func (r *Request) Root() string

Root returns the request's scheme and host, such as "https://example.com".

func (*Request) Route

func (r *Request) Route() Route

Route returns the matched Route, or the zero Route in global middleware or when no route matched. When a path matches only API routes for other HTTP methods, Route has only JSON set to true.

func (*Request) RouteField

func (r *Request) RouteField(param string) string

RouteField returns the model binding column declared after a colon in the matched route's parameter (such as "slug" for "/posts/{post:slug}"), or "" if none was specified.

func (*Request) RouteIs

func (r *Request) RouteIs(patterns ...string) bool

RouteIs reports whether the matched route's name matches any pattern in patterns, where "*" matches any sequence of characters (for example, r.RouteIs("admin.*")).

func (*Request) SentPlainCookie

func (r *Request) SentPlainCookie(name string) bool

SentPlainCookie reports whether a test client sent the cookie named name as unencrypted plain text so go.laravel.com/middleware.EncryptCookies leaves it untouched. It always returns false outside tests.

func (*Request) Session

func (r *Request) Session() *session.Session

Session returns the visitor's *session.Session. It panics if the go.laravel.com/middleware.StartSession middleware (included in the web group) did not run on this route.

func (*Request) SetCookies

func (r *Request) SetCookies(cookies []*http.Cookie)

SetCookies replaces the incoming cookie list on r. go.laravel.com/middleware.EncryptCookies calls SetCookies with decrypted cookies.

func (*Request) SetLimits

func (r *Request) SetLimits(limits Limits)

SetLimits updates the body Limits for r. It has no effect if the request body has already been read.

func (*Request) SetRoute

func (r *Request) SetRoute(route Route)

SetRoute records the matched Route on r. The router calls SetRoute during dispatch.

func (*Request) SetSession

func (r *Request) SetSession(s *session.Session)

SetSession attaches s to r. go.laravel.com/middleware.StartSession calls SetSession when loading the session.

func (*Request) Transform

func (r *Request) Transform(transform func(key string, value any) any)

Transform registers a function that runs on every input value (both query parameters and body fields), for already-parsed input and when the body or query is later parsed. The callback receives each value's dot path and returns the replacement value. Input middleware such as TrimStrings uses Transform without reading the body early.

func (*Request) User

func (r *Request) User[U any]() *U

User returns the authenticated user as *U, or nil for a guest:

user := r.User[models.User]()

Because auth.Session loads the user before the handler runs, repeated calls return the same user without additional queries. User panics if neither auth.Session nor auth.Via ran on the route, or if the route authenticates a different user type.

func (*Request) Validate

func (r *Request) Validate[T any]() (T, error)

Validate binds request body input into a new value of type T (as Request.Bind does) and validates it against the struct's rules. Validate reads only the request body; to read query string parameters, use Request.Query. Define rules via a Rules method using validation.For and [rule.Field]:

func (f *StorePost) Rules() validation.Rules {
	return validation.For(f,
		rule.Field(&f.Title, rule.Required, rule.Max(255)),
	)
}

form, err := r.Validate[StorePost]()
if err != nil {
	return web.Fail(err)
}

If the struct implements Authorize(r *web.Request) error, Validate calls it first and returns any authorization error without binding input:

func (UpdatePassword) Authorize(r *web.Request) error {
	return auth.Authenticated(r)
}

If rules depend on the request or bound fields (such as the signed-in user or a feature flag), implement Rules(r *web.Request) (validation.Rules, error). Validate calls it after binding input and returns its error without running validation:

func (f *StoreMonitor) Rules(r *web.Request) (validation.Rules, error) {
	return validation.For(f,
		rule.Field(&f.Target,
			rule.Required,
			rule.When(f.Kind == "http", rule.URL),
			rule.When(f.Kind != "http", rule.Regex(`^[A-Za-z0-9.-]+$`)),
		),
	), nil
}

Validation failures return an *InputError. Passed to Fail, browser forms redirect back with flashed errors and old input, while JSON requests receive a 422 Unprocessable Entity response.

Values that do not fit their target field type fail the corresponding type rule and skip remaining rules on that field: string, integer (or min for negative values in unsigned types), numeric for floats, boolean, array for structs and maps, list for slices and arrays, file for uploads, and invalid for encoding.TextUnmarshaler types such as time.Time. A null item in a list or map of value types, such as a null in []int64 or []Address, fails the required rule, because rules skip null and the item would otherwise hold a zero value no rule checked, and so does a null sent for a validation.Sometimes of a value type, such as a Sometimes[int] or Sometimes[Address]. Declare pointers, such as []*int64 or Sometimes[*int], to accept null.

An upload shares its path with no other input. Text at an upload's path or on the way to it, such as avatar=x beside an avatar upload, and uploads beneath another upload, such as photos[0] beside photos, fail the type rule of the field there, since the rules would check the uploads and the field would hold something else. A field for one upload, such as a *Upload, fails the file rule when the request sends several to its path, as avatar and avatar[] both do.

To validate into a struct that already holds unexported fields (such as a loaded model), use Request.ValidateInto.

func (*Request) ValidateIn

func (r *Request) ValidateIn[T any](bag string) (T, error)

ValidateIn works like Request.Validate and stores validation errors under the named error bag so multiple forms on one page display their own errors independently. Input errors the request reports later without a bag of their own, such as a failed auth.Attempt or Invalid, go in the same bag.

func (*Request) ValidateInInto

func (r *Request) ValidateInInto(bag string, dst any) error

ValidateInInto works like Request.ValidateInto and stores validation errors under the named error bag.

func (*Request) ValidateInto

func (r *Request) ValidateInto(dst any) error

ValidateInto binds and validates request body input into the struct pointed to by dst. Use ValidateInto when the form struct carries pre-populated fields, such as a loaded model used by Authorize or Rules.

ValidateInto panics if dst is not a non-nil pointer to a struct or if a rule names a field that the struct does not declare.

func (*Request) Value

func (r *Request) Value(key any) any

Value delegates to r.Context().Value(key).

func (*Request) WantsJSON

func (r *Request) WantsJSON() bool

WantsJSON reports whether JSON is the highest-priority media type in the request's Accept header.

func (*Request) WithContext

func (r *Request) WithContext(ctx context.Context) *Request

WithContext returns a shallow copy of r whose underlying *http.Request carries ctx while sharing the same request state.

func (*Request) WithHTTP

func (r *Request) WithHTTP(request *http.Request) *Request

WithHTTP returns a shallow copy of r wrapping request while sharing the same request state, such as after standard middleware modifies the *http.Request.

type Responder

type Responder interface {
	Respond(r *Request) *Response
}

Responder is an error that renders its own *Response. If Respond returns nil or a response that fails to finish, the Kernel falls back to default error rendering.

type Response

type Response struct {
	// Status is the HTTP status code. Zero defaults to 200 OK.
	Status int
	// Header holds the response headers.
	Header http.Header
	// Body holds the buffered response bytes. It is nil for files, downloads,
	// and streams written directly to the connection.
	Body []byte
	// contains filtered or unexported fields
}

Response is the HTTP response returned by a Handler. It remains a mutable value until the Kernel writes it to the network, so middleware can inspect or modify its status, headers, and cookies after the handler returns.

func Abort

func Abort(status int) *Response

Abort returns a failed *Response for the given HTTP status code:

return web.Abort(http.StatusNotFound)

func Abortf

func Abortf(status int, format string, args ...any) *Response

Abortf returns a failed *Response for status with a formatted visitor-facing message built via Errorf. Any error wrapped with %w is preserved as the underlying cause.

func Attachment

func Attachment(name string, content io.Reader) *Response

Attachment streams content as a browser download named name without buffering the full payload in memory. If content implements io.Closer, Attachment closes it when streaming finishes. Content-Type is inferred from name's extension unless set explicitly.

For a file on disk, prefer Download, which also supports Range requests.

func Back

func Back() *Response

Back returns a 302 Found redirect *Response to the visitor's previous page: the request's Referer header, falling back to the session's previous URL, and finally to the application root ("/").

func Created

func Created(value any) *Response

Created marshals value to JSON and returns a 201 Created *Response.

func DiskDownload

func DiskDownload(disk *storage.Disk, path, name string) *Response

DiskDownload streams a file from disk as a browser download saved under name, or under the base name of path when name is empty. Range requests, conditional requests, and error handling behave like DiskFile:

return web.DiskDownload(storage.From(r), fmt.Sprintf("invoices/%d.pdf", invoice.ID), "Invoice.pdf")

Authorize the visitor before returning DiskDownload.

func DiskFile

func DiskFile(disk *storage.Disk, path string) *Response

DiskFile streams a file from disk for inline display in the browser, such as a PDF or image:

return web.DiskFile(storage.From(r), "reports/monthly.pdf")

DiskFile uses the content type reported by disk unless you set Content-Type on the response. It supports HTTP Range and conditional requests, returns 404 Not Found when path does not exist, and sets a sandboxed Content-Security-Policy header so stored HTML cannot execute scripts on your origin.

func Download

func Download(path, name string) *Response

Download serves the local file at path as a browser download saved under name, or under the file's own base name when name is empty. Relative path resolution, Range requests, and 404 behavior match File.

To delete a temporary file after the response finishes, register cleanup with Request.OnFinish:

r.OnFinish(func() { os.Remove(path) })

func Events

func Events(events iter.Seq[Event]) *Response

Events returns a server-sent events *Response for browsers consuming an EventSource stream:

return web.Events(func(yield func(web.Event) bool) {
	for task := range tasks {
		if !yield(web.Event{Name: "task-added", Data: task}) {
			return
		}
	}
})

The stream ends when events finishes, the client disconnects, or the server begins shutting down. When the producer can return an error, use StreamEvents instead.

func Fail

func Fail(err error) *Response

Fail turns err into an error *Response that Handler.Respond renders as an HTML error page, a JSON error payload, or a form validation redirect:

if err != nil {
	return web.Fail(err)
}

Server errors (5xx) are reported automatically, except for an *Error without an underlying Err (which represents an explicit status chosen by the handler). Outside debug mode, server error responses display only "Server Error". In debug mode, they include the error message, Go type, and any panic stack trace.

Errors caused by request context cancellation are not reported: client disconnects log status 499, and route timeouts or server shutdown deadlines render 503 Service Unavailable. Reported error logs include the caller's file and line as "location".

When a unit test invokes a handler directly without a Kernel, the returned *Response has Status set to StatusOf(err) and Response.Cause returns err.

func File

func File(path string) *Response

File serves the local file at path inline in the browser, supporting HTTP Range and conditional requests. Content-Type is inferred from the filename unless set explicitly. Relative paths resolve against the application base path, and missing files return 404 Not Found.

func HTML

func HTML(html string) *Response

HTML returns a 200 OK HTML *Response with Content-Type "text/html; charset=utf-8".

func Invalid

func Invalid(field, message string) *Response

Invalid returns a failed *Response attaching message as a validation error on field, matching the response produced by a failed Request.Validate:

if startsOn.Before(today) {
	return web.Invalid("starts_on", "The arrival date can't be in the past.")
}

To report errors on multiple fields or in a named error bag, call Fail with an *InputError.

func InvalidErrors

func InvalidErrors(fields validation.Errors) *Response

InvalidErrors returns a failed *Response attaching fields as validation errors, matching the response produced by a failed Request.Validate:

var invalid validation.Errors
invalid.Add("starts_on", "The arrival date can't be in the past.")
if len(invalid) > 0 {
	return web.InvalidErrors(invalid)
}

func JSON

func JSON(value any) *Response

JSON marshals value to JSON and returns a 200 OK *Response with Content-Type "application/json". If marshaling fails, the response renders as a 500 Internal Server Error.

func NoContent

func NoContent() *Response

NoContent returns an empty 204 No Content *Response.

func Proxy

func Proxy(res *http.Response) *Response

Proxy streams an upstream *http.Response directly to the client with its status code, headers, and body:

res, err := httpclient.EnsureSuccessful().Stream(r, http.MethodGet, "https://files.example.com/reports/42.pdf")
if err != nil {
	return web.Fail(err)
}

return web.Proxy(res)

The upstream body is streamed without buffering the full payload in memory and is closed when streaming finishes or the client disconnects. Proxy strips hop-by-hop headers (such as Connection and Transfer-Encoding) and Set-Cookie so upstream cookies cannot be set on your domain. You can chain status or header changes on the returned *Response before returning it.

func Redirect

func Redirect(location string) *Response

Redirect returns a 302 Found redirect *Response to location.

func RedirectRoute

func RedirectRoute(name string, params ...any) *Response

RedirectRoute returns a 302 Found redirect *Response to the named route, accepting route parameters the same way as urls.Route:

return web.RedirectRoute("posts.show", "post", &post)

If the route name or parameters are invalid, the response renders as a 500 Internal Server Error.

func Stream

func Stream(produce func(w io.Writer) error) *Response

Stream returns a *Response whose body is written incrementally after the handler returns, flushing each write to the client immediately:

return web.Stream(func(w io.Writer) error {
	for _, step := range steps {
		if _, err := fmt.Fprintln(w, step); err != nil {
			return err
		}
	}

	return nil
})

Writes fail once the client disconnects, so returning the write error stops the stream cleanly. Any other error returned by produce is reported and aborts the HTTP connection so the client knows the response was truncated.

Stream defaults to "text/plain; charset=utf-8" unless you set Content-Type. Because the session is saved before streaming begins, make any session changes in the handler rather than inside produce.

func StreamDownload

func StreamDownload(name string, produce func(w io.Writer) error) *Response

StreamDownload streams generated content as a browser download named name, such as a CSV export of database rows:

return web.StreamDownload("users.csv", func(w io.Writer) error {
	rows := csv.NewWriter(w)
	// Write each user...
	rows.Flush()

	return rows.Error()
})

Streaming lifecycle and error handling match Stream. Content-Type is inferred from name's extension unless set explicitly.

func StreamEvents

func StreamEvents(produce func(send func(Event) error) error) *Response

StreamEvents returns a server-sent events *Response produced by a function that calls send for each event and may return an error:

return web.StreamEvents(func(send func(web.Event) error) error {
	for event, err := range httpclient.Events(res.Body) {
		if err != nil {
			return err
		}
		if err := send(web.Event{Data: event.Data}); err != nil {
			return err
		}
	}

	return nil
})

send fails once the client disconnects, so returning its error stops the stream cleanly. Returning any other error reports it and ends the stream without sending the final "</stream>" event.

func StreamJSON

func StreamJSON[T any](items iter.Seq2[T, error]) *Response

StreamJSON streams a JSON array one item at a time so large result sets (such as a query's LazyByID iterator) do not need to fit in memory:

return web.StreamJSON(model.Query[models.User]().LazyByID(r, 500))

Any error yielded by items is reported and aborts the connection so the client detects the truncated stream. To wrap the array in an object key, use JSONStream.

func Text

func Text(text string) *Response

Text returns a 200 OK plain-text *Response with Content-Type "text/plain; charset=utf-8".

func View

func View(name string, data any) *Response

View returns an HTML *Response that renders the named view (resources/views/<name>.html) with data:

return web.View("posts.create", tags)

The view renders immediately after the handler returns, before outer route middleware runs, with the request context attached so template helpers such as csrfField and old can inspect the request. A rendering error turns the response into a 500 Internal Server Error.

func (*Response) Cause

func (res *Response) Cause() error

Cause returns the error that produced Laravel's built-in error page or JSON error response, or nil for normal responses and custom responses built by Responder or Errors.Render. On an unrendered Fail response returned directly by a handler in a unit test, Cause returns the underlying error.

func (*Response) Cookies

func (res *Response) Cookies() []*http.Cookie

Cookies returns the slice of cookies attached to res. Middleware may replace elements of the returned slice in place.

func (*Response) Fragment

func (res *Response) Fragment(names ...string) *Response

Fragment restricts a View response to render only the named {{define}} blocks, such as a form fragment swapped in place after a failed submission. Unknown block names render nothing. Fragment has no effect on non-view responses.

func (*Response) Then

func (res *Response) Then(finish func(r *Request, res *Response) error) *Response

Then registers a finalization hook that runs when the response meets its *Request, before outer route middleware inspects it. Custom response builders use Then to read the request's session or headers:

func Page(component string) *web.Response {
	return web.HTML("").Then(func(r *web.Request, res *web.Response) error {
		// ...
	})
}

Returning an error from finish replaces res with the rendered error response.

func (*Response) With

func (res *Response) With(key string, value any) *Response

With flashes value under key to the session for the next request, typically paired with a redirect:

return web.Back().With("status", "Profile saved.")

With requires a session on the route; if no session is present, it logs a warning and drops the value.

func (*Response) WithCookie

func (res *Response) WithCookie(cookie *http.Cookie) *Response

WithCookie attaches cookie to res, replacing any previously attached cookie with the same name, path, and domain. Construct cookies with package cookie:

return web.Text("Saved").WithCookie(cookie.Forever("theme", "dark"))

When the response is written, unset Path, Domain, SameSite, and Secure attributes inherit the session cookie defaults. Cookies larger than 4096 bytes fail the request in debug and testing environments and are reported in production.

func (*Response) WithError

func (res *Response) WithError(field, message string) *Response

WithError attaches a validation error message for field to res.

On a view response, template error helpers (error and errors) read directly from the attached errors instead of session flash data. On any other response (such as a redirect), WithError flashes the error to the session for the next request, matching Response.With and Response.WithInput:

return web.Back().WithError("coupon", "That coupon has expired.").WithInput()

Chaining WithError or combining it with Response.WithErrors accumulates each error in order.

func (*Response) WithErrors

func (res *Response) WithErrors(invalid *InputError) *Response

WithErrors attaches validation errors from invalid to res.

On a view response, template error helpers (error and errors) read directly from invalid instead of session flash data, useful when re-rendering a form fragment in place rather than redirecting:

form, err := r.Validate[StorePost]()
if err != nil {
	invalid, ok := errors.AsType[*web.InputError](err)
	if !ok {
		return web.Fail(err)
	}
	return web.View("posts.create", form).Fragment("form").WithErrors(invalid).
		WithStatus(http.StatusUnprocessableEntity)
}

On any other response (such as a redirect to a custom destination), WithErrors flashes the errors to the session for the next request, matching Response.With and Response.WithInput:

return web.Redirect("/cart").WithErrors(invalid).WithInput()

Chaining WithErrors or combining it with Response.WithError accumulates errors in the same bag in order.

func (*Response) WithFragment

func (res *Response) WithFragment(fragment string) *Response

WithFragment appends or replaces the URL fragment (after "#") on a redirect response's Location header.

func (*Response) WithHeader

func (res *Response) WithHeader(key, value string) *Response

WithHeader sets header key to value on res, replacing any existing values, and returns res.

func (*Response) WithInput

func (res *Response) WithInput() *Response

WithInput flashes the request's body input to the session as old form input for the next request. Password fields and keys listed in Errors.DontFlash are excluded automatically.

func (*Response) WithQuery

func (res *Response) WithQuery(query url.Values) *Response

WithQuery appends URL-encoded query parameters to a redirect response's Location header, placing them before any "#" fragment. Empty query values leave the Location header unchanged.

func (*Response) WithStatus

func (res *Response) WithStatus(status int) *Response

WithStatus sets the HTTP status code on res and returns res.

func (*Response) WithoutCookie

func (res *Response) WithoutCookie(name string) *Response

WithoutCookie attaches an expired cookie instructing the browser to remove the cookie named name using the session cookie's default path and domain. For cookies set with a custom path or domain, pass cookie.Forget to Response.WithCookie with those attributes set.

type Route

type Route struct {
	// Name is the route's registered name, such as "users.show", or "".
	Name string
	// URI is the route's registered path pattern, such as "/users/{user}".
	URI string
	// Domain is the route's registered host pattern, or "" if domainless.
	Domain string
	// Methods lists the HTTP methods the route handles, including HEAD for
	// GET routes. An empty slice matches all methods.
	Methods []string
	// Handler is the qualified name of the route's handler, such as
	// "app/handlers/users.Show".
	Handler string
	// Middleware lists the route's middleware names in execution order
	// (outermost first), excluding global middleware that runs before routing.
	Middleware []string
	// Standard reports whether the route is served by a standard
	// [http.Handler] mounted via Router.Handle. When true, [Request.ParseInput]
	// leaves the request body unread for the handler.
	Standard bool
	// Fields maps route parameter names to their explicit model binding
	// columns (for example, "{post:slug}" maps "post" to "slug").
	Fields map[string]string
	// JSON reports whether the route always renders errors as JSON regardless
	// of the Accept header.
	JSON bool
}

Route describes the matched route for an incoming Request.

type Stack

type Stack []Middleware

Stack is an ordered list of Middleware, executed from index 0 (outermost) toward the handler.

func (*Stack) Append

func (s *Stack) Append(middleware ...Middleware)

Append adds middleware to the end of the stack, closest to the handler.

func (Stack) Names

func (s Stack) Names() []string

Names returns the qualified type or function name of each middleware in s in execution order, such as "go.laravel.com/middleware.ValidateCSRFToken".

func (*Stack) Prepend

func (s *Stack) Prepend(middleware ...Middleware)

Prepend adds middleware to the beginning of the stack, outermost from the handler.

func (*Stack) Remove

func (s *Stack) Remove(middleware ...Middleware)

Remove deletes every middleware from the stack matching the concrete type of any entry in middleware. Struct field values are ignored, so passing middleware.TrimStrings{} removes any TrimStrings regardless of its settings.

func (*Stack) Replace

func (s *Stack) Replace(m Middleware) bool

Replace swaps every middleware in the stack matching m's concrete type with m in place, and reports whether any entry was replaced.

type Upload

type Upload struct {
	// Name is the base filename supplied by the client, stripped of any
	// directory path. Treat Name as untrusted input and never use it directly
	// as a filesystem path.
	Name string
	// Size is the uploaded file's size in bytes.
	Size int64
	// contains filtered or unexported fields
}

Upload represents a file uploaded in a multipart HTTP request. Laravel stores the upload in a temporary file until the response finishes, so copy or store it with Upload.Store or Upload.StoreAs before returning.

func (*Upload) Attachment

func (u *Upload) Attachment() httpclient.Attachment

Attachment builds an httpclient.Attachment for forwarding the uploaded file in an outgoing HTTP request using its original filename and detected MIME type:

res, err := httpclient.Attach("photo", form.Photo.Attachment()).Post(r, "https://storage.example.com/photos")

Send the outgoing request before the current handler returns, because the temporary file is deleted once the response finishes.

func (*Upload) ContentType

func (u *Upload) ContentType() string

ContentType detects and returns the file's MIME type (such as "image/png") by inspecting its bytes, ignoring the client-supplied Content-Type header.

func (*Upload) Extension

func (u *Upload) Extension() string

Extension returns the file extension matching the detected file bytes (such as "png"), or "" if the file type is unknown.

func (*Upload) Open

func (u *Upload) Open() (*os.File, error)

Open opens the temporary upload file for reading.

func (*Upload) Path

func (u *Upload) Path() string

Path returns the temporary filesystem path where the uploaded file lives until the request completes.

func (*Upload) Store

func (u *Upload) Store(ctx context.Context, disk *storage.Disk, directory string) (string, error)

Store writes the uploaded file to disk under directory using a random 40-character filename with Upload.Extension, and returns its path on disk:

path, err := form.Avatar.Store(r, storage.From(r).Disk("public"), "avatars")

Pass "" for directory to store at the disk root.

func (*Upload) StoreAs

func (u *Upload) StoreAs(ctx context.Context, disk *storage.Disk, directory, name string) (string, error)

StoreAs writes the uploaded file to disk at directory/name, overwriting any existing file, and returns the resulting path on disk. Do not pass the untrusted Upload.Name as name.

type Views

type Views interface {
	// Has reports whether a view named name exists.
	Has(name string) bool
	// Render writes the rendered view named name with data to w. When
	// fragments are given, it renders only those {{define}} blocks.
	Render(ctx context.Context, w io.Writer, name string, data any, fragments ...string) error
}

Views renders HTML templates by dot-separated name, such as "posts.show" for resources/views/posts/show.html.

Jump to

Keyboard shortcuts

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