Documentation
¶
Index ¶
- Constants
- Variables
- type Context
- type Controller
- func (c *Controller) DelSession(name interface{})
- func (c *Controller) Finish()
- func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader, error)
- func (c *Controller) GetSession(name interface{}) interface{}
- func (c *Controller) GetString(key string, def ...string) string
- func (c *Controller) Init(ctx *Context, controllerName, actionName string, app interface{})
- func (c *Controller) Input() url.Values
- func (c *Controller) Prepare()
- func (c *Controller) ServeJSON(encoding ...bool)
- func (c *Controller) SetSession(name interface{}, value interface{})
- func (c *Controller) StartSession() Store
- func (c *Controller) StopRun()
- type ControllerInterface
- type FilterFunc
- type Input
- func (input *Input) CopyBody(maxMemory int64) []byte
- func (input *Input) Data() map[interface{}]interface{}
- func (input *Input) GetData(key interface{}) interface{}
- func (input *Input) Header(key string) string
- func (input *Input) Method() string
- func (input *Input) Param(key string) string
- func (input *Input) Params() map[string]string
- func (input *Input) Query(key string) string
- func (input *Input) Reset(ctx *Context)
- func (input *Input) Scheme() string
- func (input *Input) Session(key interface{}) interface{}
- func (input *Input) SetData(key, val interface{})
- func (input *Input) SetParam(key, val string)
- func (input *Input) URL() string
- type MemorySessions
- type Output
- func (output *Output) Body(content []byte) error
- func (output *Output) Cookie(name, value string, others ...interface{})
- func (output *Output) Header(key, val string)
- func (output *Output) JSON(data interface{}, hasIndent bool, encoding bool) error
- func (output *Output) Reset(ctx *Context)
- func (output *Output) SetStatus(status int)
- type Response
- type Router
- func (p *Router) InsertFilter(pattern string, pos int, filter FilterFunc, params ...bool) error
- func (p *Router) Patterns() map[string][]string
- func (p *Router) Router(pattern string, c ControllerInterface, mapping string)
- func (p *Router) ServeHTTP(rw http.ResponseWriter, r *http.Request)
- func (p *Router) UseSessions(m SessionManager)
- type SessionManager
- type Store
Constants ¶
const ( BeforeStatic = iota BeforeRouter BeforeExec AfterExec FinishRouter )
Filter positions, ordered as they run around a request.
const ModeProd = "prod"
ModeProd is the run mode under which ServeJSON omits indentation.
Variables ¶
var ErrAbort = errors.New("web: stop run")
ErrAbort is the panic value StopRun raises to unwind a handler; the router recovers it and stops running the request without treating it as a crash.
var RunMode = ModeProd
RunMode selects response formatting: any value other than ModeProd pretty-prints ServeJSON output. It defaults to ModeProd (compact), matching the runtime default; the serving layer sets it from config when configured.
Functions ¶
This section is empty.
Types ¶
type Context ¶
Context carries one request's reader and writer: the Input for request data, the Output for the response, and the raw Request plus the wrapped ResponseWriter.
func NewContext ¶
func NewContext() *Context
NewContext returns a Context with an initialized Input and Output.
type Controller ¶
type Controller struct {
Ctx *Context
Data map[interface{}]interface{}
CruSession Store
// EnableRender is retained for handler compatibility. Handlers write their
// own responses (ServeJSON, Output.Body), so the router renders nothing;
// toggling this flag has no effect on the response.
EnableRender bool
AppController interface{}
// contains filtered or unexported fields
}
Controller is the base a request handler embeds. It holds the request Context, the response Data bag and the session store.
func (*Controller) DelSession ¶
func (c *Controller) DelSession(name interface{})
DelSession deletes a session value.
func (*Controller) Finish ¶
func (c *Controller) Finish()
Finish runs after the handler. The base does nothing; a controller may override it.
func (*Controller) GetFile ¶ added in v1.822.2
func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader, error)
GetFile returns the uploaded multipart file for a form key.
func (*Controller) GetSession ¶
func (c *Controller) GetSession(name interface{}) interface{}
GetSession returns a session value, or nil when no session is bound.
func (*Controller) GetString ¶
func (c *Controller) GetString(key string, def ...string) string
GetString returns a route parameter or form value for key, or the optional default when unset.
func (*Controller) Init ¶
func (c *Controller) Init(ctx *Context, controllerName, actionName string, app interface{})
Init binds the controller to a request. Data aliases the Input's per-request map, so values set through Ctx.Input.SetData and c.Data are the same map.
func (*Controller) Input ¶
func (c *Controller) Input() url.Values
Input parses and returns the request form values (query plus body form).
func (*Controller) Prepare ¶
func (c *Controller) Prepare()
Prepare runs before the handler. The base does nothing; a controller may override it.
func (*Controller) ServeJSON ¶
func (c *Controller) ServeJSON(encoding ...bool)
ServeJSON writes c.Data["json"] as the JSON response body, indented unless the run mode is prod. Passing true escapes non-ASCII runes.
func (*Controller) SetSession ¶
func (c *Controller) SetSession(name interface{}, value interface{})
SetSession stores a session value.
func (*Controller) StartSession ¶
func (c *Controller) StartSession() Store
StartSession binds the request session store, taking it from the Input on first use, and returns it.
func (*Controller) StopRun ¶
func (c *Controller) StopRun()
StopRun unwinds the current handler via a recovered panic.
type ControllerInterface ¶
type ControllerInterface interface {
Init(ctx *Context, controllerName, actionName string, app interface{})
Prepare()
Finish()
}
ControllerInterface is the contract the router drives per request: build the controller with Init, run Prepare before the handler and Finish after.
type FilterFunc ¶
type FilterFunc func(*Context)
FilterFunc runs against a request context at a filter position.
type Input ¶
type Input struct {
Context *Context
CruSession Store
RequestBody []byte
// contains filtered or unexported fields
}
Input reads the request line, headers, route parameters, per-request data and the cached body for one request.
func (*Input) CopyBody ¶
CopyBody reads the request body once (up to maxMemory, transparently gunzipping a gzip-encoded body), caches it on RequestBody, and rewinds Request.Body from the cache so later readers see the same bytes.
func (*Input) Data ¶
func (input *Input) Data() map[interface{}]interface{}
Data returns the per-request data map, allocating it on first use.
func (*Input) GetData ¶
func (input *Input) GetData(key interface{}) interface{}
GetData returns a per-request value, or nil when the key is unset.
func (*Input) Query ¶
Query returns a route parameter of the key, or the parsed form/query value when no such parameter exists.
func (*Input) Scheme ¶
Scheme returns the request scheme, preferring the X-Forwarded-Proto header, then the URL scheme, then "https" when the connection is TLS, else "http".
func (*Input) Session ¶
func (input *Input) Session(key interface{}) interface{}
Session returns a session value for key, or nil when no session is bound. A missing store yields nil rather than a panic, so an unauthenticated request resolves to "no session value" and falls through to credential auth.
func (*Input) SetData ¶
func (input *Input) SetData(key, val interface{})
SetData stores a per-request value.
type MemorySessions ¶ added in v1.823.0
type MemorySessions struct {
// contains filtered or unexported fields
}
MemorySessions is a cookie-keyed, in-memory session manager. It backs the cookie web-admin flow (API requests authenticate per-request via bearer credentials, not sessions). Single-process by design, matching the single-replica runtime.
var Sessions *MemorySessions
Sessions is the process session manager. The runtime sets it and binds it to the router; the logout path reaches it for SessionDestroy.
func NewMemorySessions ¶ added in v1.823.0
func NewMemorySessions(cookieName string, maxAge time.Duration) *MemorySessions
NewMemorySessions builds a session manager for a cookie name and lifetime and starts its expiry sweep.
func (*MemorySessions) SessionDestroy ¶ added in v1.823.0
func (m *MemorySessions) SessionDestroy(id string) error
SessionDestroy removes a session by id (the logout path).
func (*MemorySessions) SessionStart ¶ added in v1.823.0
func (m *MemorySessions) SessionStart(w http.ResponseWriter, r *http.Request) (Store, error)
SessionStart returns the session named by the request cookie, or creates a new one and sets the cookie on the response.
type Output ¶
Output writes the response status, headers and body. Response compression is handled at the edge (the cloud/gateway serving layer), so Output writes bodies uncompressed.
func (*Output) Body ¶
Body writes content as the response body. It sets Content-Length, sends a status set earlier via SetStatus (then clears it so a second write cannot emit a duplicate status line), and writes the bytes.
func (*Output) Cookie ¶ added in v1.822.2
Cookie adds a Set-Cookie response header. The optional args are positional, in order: max-age (int seconds; negative deletes), path (string, default "/"), domain (string), secure (bool) and http-only (bool).
func (*Output) JSON ¶
JSON writes data as a JSON body. hasIndent pretty-prints; encoding escapes non-ASCII runes to \uXXXX. A marshal error becomes a 500.
type Response ¶
type Response struct {
http.ResponseWriter
Started bool
Status int
}
Response wraps http.ResponseWriter and records whether the reply has begun (Started) and the status written (Status). It passes Flush, Hijack, CloseNotify and Pusher through to the underlying writer so streaming and server-sent-event handlers keep working.
func (*Response) Flush ¶
func (r *Response) Flush()
Flush forwards to the underlying writer when it is an http.Flusher, so streaming responses can push buffered bytes.
func (*Response) WriteHeader ¶
WriteHeader sends the status line once; a second call is ignored so the handler chain cannot emit two WriteHeader calls.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router registers controllers and filters and serves requests: it builds a per-request Context, runs the filter chain around a reflection-dispatched controller method, and is itself an http.Handler.
func (*Router) InsertFilter ¶
InsertFilter adds a filter at a position for a URL pattern. The optional first bool is returnOnOutput (default true): a true filter that writes the response short-circuits the chain.
func (*Router) Patterns ¶ added in v1.831.12
Patterns returns every registered route pattern, in registration order, with its methods — e.g. "/v1/ai/stores" -> ["GET","POST"].
Exported so a caller can assert things ABOUT its own route table that the table cannot see from the inside: most usefully, that a generated route never lands on a pattern a hand-written one already claimed. Two registrations of one pattern do not error here — the more specific, or the earlier, simply wins — so without a check like that the loser is silently unreachable.
func (*Router) Router ¶
func (p *Router) Router(pattern string, c ControllerInterface, mapping string)
Router registers a controller for a URL pattern with a method mapping such as "GET:List;POST:Create". The controller value supplies the type that is freshly instantiated per request.
func (*Router) ServeHTTP ¶
func (p *Router) ServeHTTP(rw http.ResponseWriter, r *http.Request)
ServeHTTP builds the request context, caches the body, runs the filter chain around the matched controller method, and recovers a StopRun abort or a handler panic.
func (*Router) UseSessions ¶ added in v1.822.2
func (p *Router) UseSessions(m SessionManager)
UseSessions binds a session manager. When set, ServeHTTP starts a session before the filter chain (so the auth filters and controllers read it) and releases it after the response.
type SessionManager ¶ added in v1.822.2
type SessionManager interface {
SessionStart(w http.ResponseWriter, r *http.Request) (Store, error)
}
SessionManager starts the session store for a request. A provider that matches this shape (the session provider does) binds per-request sessions without the router depending on the provider.
type Store ¶
type Store interface {
Set(key, value interface{}) error
Get(key interface{}) interface{}
Delete(key interface{}) error
SessionID() string
SessionRelease(w http.ResponseWriter)
Flush() error
}
Store is the per-request session store bound to Input.CruSession. Its shape is the session-provider contract, so a provider satisfies it unchanged.