Context
type Context
type Context interface {
// Request returns the `*http.Request` instance for the current request.
Request() *http.Request
// SetRequest sets the `*http.Request` instance.
SetRequest(r *http.Request)
// Response returns `slim.ResponseWriter`.
Response() ResponseWriter
// SetResponse sets `slim.ResponseWriter`.
SetResponse(r ResponseWriter)
// Filesystem returns `fs.FS`.
Filesystem() fs.FS
// SetFilesystem sets `fs.FS`
SetFilesystem(fs.FS)
// IsTLS returns true if the HTTP connection is TLS, otherwise false.
IsTLS() bool
// IsWebSocket returns true if the HTTP connection is WebSocket, otherwise false.
IsWebSocket() bool
// Scheme returns the HTTP protocol scheme, `http` or `https`.
Scheme() string
// RealIP returns the client's network address based on `X-Forwarded-For` or `X-Real-IP` request header.
// The behavior can be configured using `Slim#IPExtractor`.
RealIP() string
RequestMethod() string
RequestURI() string
// Is checks if the request Content-Type matches the given types
Is(types ...string) string
// Accepts returns the media type with the highest weight that is supported, or returns an empty string if no match is found.
// The provided values can be standard media types (like application/json) or extensions (like json, xml, etc.).
Accepts(expect ...string) string
// AcceptsEncodings returns the encoding with the highest weight that is supported, or returns an empty string if no match is found.
AcceptsEncodings(encodings ...string) string
// AcceptsCharsets returns the charset with the highest weight that is supported, or returns an empty string if no match is found.
AcceptsCharsets(charsets ...string) string
// AcceptsLanguages returns the language with the highest weight that is supported, or returns an empty string if no match is found.
AcceptsLanguages(languages ...string) string
// AllowsMethods returns the allowed request methods
AllowsMethods() []string
// RouteMatchType returns the result of router matching
RouteMatchType() RouteMatchType
// RouteInfo returns route information for the current request. Returns method, path, name, and parameters if a route is matched.
// In 404 (route not found) and 405 (method not allowed) cases, RouteInfo returns a generic struct for these scenarios.
RouteInfo() RouteInfo
// PathParam returns a path parameter by name.
PathParam(name string) string
// PathParams returns path parameter values.
PathParams() PathParams
// SetPathParams sets path parameters during the current request lifecycle.
SetPathParams(params PathParams)
// QueryParam returns the query parameter for the provided name.
QueryParam(name string) string
// QueryParams returns query parameters as `url.Values`.
QueryParams() url.Values
// QueryString returns the URL query string.
QueryString() string
// FormValue returns the form field value for the provided name.
FormValue(name string) string
// FormParams returns form parameters as `url.Values`.
FormParams() (url.Values, error)
// FormFile returns the multipart form file for the provided name.
FormFile(name string) (*multipart.FileHeader, error)
Header(key string) string
SetHeader(key string, values ...string)
// MultipartForm returns the multipart form.
MultipartForm() (*multipart.Form, error)
// Cookie returns the cookie with the specified name from the request.
Cookie(name string) (*http.Cookie, error)
// SetCookie adds a `Set-Cookie` header in the HTTP response.
SetCookie(cookie *http.Cookie)
// Cookies returns the HTTP cookies sent with the request.
Cookies() []*http.Cookie
// Get retrieves data from the context.
Get(key string) any
// Set saves data in the context.
Set(key string, val any)
// Bind binds the request body to the provided type `i`. The default binder
// performs this based on the Content-Type header.
Bind(i any) error
// Validate validates the provided `i`. Typically called after `Context#Bind()`.
// A validator must be registered with `Slim#Validator`.
Validate(i any) error
// Written returns whether the context response has been written
Written() bool
// Render renders a template with data and sends a text/html response with status code.
// A renderer must be registered with `Slim.Renderer`.
Render(code int, name string, data any) error
// HTML sends an HTTP response with status code.
HTML(code int, html string) error
// HTMLBlob sends an HTTP blob response with status code.
HTMLBlob(code int, b []byte) error
// String sends a string response with status code.
String(code int, s string) error
// JSON sends a JSON response with status code.
JSON(code int, i any) error
// JSONPretty sends a formatted JSON with status code.
JSONPretty(code int, i any, indent string) error
// JSONBlob sends a JSON blob response with status code.
JSONBlob(code int, b []byte) error
// JSONP sends a JSONP response with status code. It uses `callback` to construct
// the JSONP payload.
JSONP(code int, callback string, i any) error
// JSONPBlob sends a JSONP blob response with status code. It uses `callback`
// to construct the JSONP payload.
JSONPBlob(code int, callback string, b []byte) error
// XML sends an XML response with status code.
XML(code int, i any) error
// XMLPretty sends a formatted XML with status code.
XMLPretty(code int, i any, indent string) error
// XMLBlob sends an XML blob response with status code.
XMLBlob(code int, b []byte) error
// Blob sends a blob response with status code and content type.
Blob(code int, contentType string, b []byte) error
// Stream sends a streaming response with status code and content type.
Stream(code int, contentType string, r io.Reader) error
// File sends a response with file content.
File(file string, filesystem ...fs.FS) error
// Attachment sends a response as an attachment, prompting the client to save the file.
Attachment(file string, name string) error
// Inline sends a response as inline, opening the file in the browser.
Inline(file string, name string) error
// NoContent sends a response without body and status code.
NoContent(code ...int) error
// Redirect redirects the request to the provided URL with status code.
Redirect(code int, url string) error
// Error invokes the registered HTTP error handler.
// Note: Avoid using this method. It's better to return an error so middleware in the chain can take action on the returned error.
Error(err error)
// Slim returns the Slim instance
Slim() *Slim
}
The Context interface represents the context of the current HTTP request. It contains references to the request and response objects, path, path parameters, data, and matched route information.
type EditableContext
type EditableContext interface {
Context
// RawPathParams returns raw path parameter values.
RawPathParams() *PathParams
// SetRawPathParams replaces any existing parameter values with new values during this context lifecycle (request).
SetRawPathParams(params *PathParams)
// SetRouteMatchType sets the RouteMatchType for the router match of this request.
SetRouteMatchType(t RouteMatchType)
SetAllowsMethods(methods []string)
// SetRouteInfo sets route information for this request to the context.
SetRouteInfo(ri RouteInfo)
// Reset resets the context after the request is completed. Must be called with `Slim#AcquireContext()` and `Slim#ReleaseContext()`.
// See `Slim#ServeHTTP()`
Reset(w http.ResponseWriter, r *http.Request)
}
type PathParam
type PathParam struct {
Name string
Value string
}
Route parameter unit struct.
type PathParams
type PathParams []PathParam
func (PathParams) Get
func (p PathParams) Get(name string, defaultValue ...string) string
Gets path parameter. If the parameter doesn't exist, uses the provided default value. If no default value is provided, returns an empty string.
func (PathParams) Lookup
func (p PathParams) Lookup(name string) (string, bool)
Gets path parameter. The second return value indicates whether the provided name exists.
type contextImpl
type contextImpl struct{}
Default context struct that implements both the Context and EditableContext interfaces.
contextImpl embeds the standard library's context.Context interface, implemented through c.Request().Context().
func (*contextImpl) Request
func (c *contextImpl) Request() *http.Request
Returns the *http.Request instance for the current request.
func (*contextImpl) SetRequest
func (c *contextImpl) SetRequest(r *http.Request)
Sets the *http.Request instance.
func (*contextImpl) Response
func (c *contextImpl) Response() ResponseWriter
Returns the implementation of the slim.ResponseWriter interface, which wraps the http.ResponseWriter instance and also implements both the http.Flusher and http.Pusher interfaces.
func (*contextImpl) SetResponse
func (c *contextImpl) SetResponse(r ResponseWriter)
Sets a custom slim.ResponseWriter.
func (*contextImpl) Filesystem
func (c *contextImpl) Filesystem() fs.FS
Returns the fs.FS filesystem interface.
func (*contextImpl) SetFilesystem
func (c *contextImpl) SetFilesystem(fs.FS)
Sets the fs.FS filesystem interface.
func (*contextImpl) IsTLS
func (c *contextImpl) IsTLS() bool
Returns true if the HTTP connection is TLS, otherwise returns false.
func (*contextImpl) IsWebSocket
func (c *contextImpl) IsWebSocket() bool
Returns true if it's a WebSocket connection, otherwise returns false.
func (*contextImpl) Scheme
func (c *contextImpl) Scheme() string
Returns the HTTP protocol scheme, either http or https.
func (*contextImpl) RealIP
func (c *contextImpl) RealIP() string
Returns the client's IP address based on the X-Forwarded-For and X-Real-IP headers.
func (*contextImpl) RequestMethod
func (c *contextImpl) RequestMethod() string
Returns the request method.
func (*contextImpl) RequestURI
func (c *contextImpl) RequestURI() string
Returns the complete request URI string.
func (*contextImpl) Accepts
func (c *contextImpl) Accepts(expect ...string) string
Returns the media type with the highest weight that is supported, or returns an empty string if no match is found. The expect parameter values can be standard media types (like application/json) or extensions (like json, xml, etc.).
For specific logic, refer to the interface Negotiation
// Accept: text/html
c.accepts("html")
// => "html"
// Accept: text/*, application/json
c.accepts("html")
// => "html"
c.accepts("text/html")
// => "text/html"
c.accepts("json", "text")
// => "json"
c.accepts("application/json")
// => "application/json"
// Accept: text/*, application/json
c.accepts("image/png")
c.accepts("png")
// => false
// Accept: text/*;q=.5, application/json
c.accepts("html", "json")
// => "json"
// No Accept header
c.accepts("html", "json")
// => ""
c.accepts("json", "html")
// => ""
In some cases, when different behaviors are needed based on content negotiation, we can use switch:
switch(c.accepts("json", "html", "text")) {
case "json":
case "html":
case "text":
default:
}
func (*contextImpl) AcceptsEncodings
func (c *contextImpl) AcceptsEncodings(encodings ...string) string
Returns the encoding with the highest weight supported by the current request, or returns an empty string if no match is found.
// Accept-Encoding: gzip
c.acceptsEncodings("gzip", "deflate", "identity")
// => "gzip"
func (*contextImpl) AcceptsCharsets
func (c *contextImpl) AcceptsCharsets(charsets ...string) string
Returns the charset with the highest weight that is supported, or returns an empty string if no match is found.
// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
c.acceptsCharsets("utf-8", "utf-7")
// => "utf-8"
func (*contextImpl) AcceptsLanguages
func (c *contextImpl) AcceptsLanguages(languages ...string) string
Returns the language with the highest weight that is supported, or returns an empty string if no match is found.
// Accept-Language: en;q=0.8, es, pt
c.acceptsLanguages("es", "en")
// => "es"
func (*contextImpl) AllowsMethods
func (c *contextImpl) AllowsMethods() []string
Returns all request methods supported by the current request path (including HTTP methods supported by routes that match the path and HTTP methods supported by routes that don't match).
func (*contextImpl) RouteMatchType
func (c *contextImpl) RouteMatchType() RouteMatchType
Returns the result of router matching, which we can use to determine which approach to use to complete the current request:
- RouteMatchFound - Successfully matched a defined route through the current request's path and method;
- RouteMatchNotFound - No route matches the current request path;
- RouteMatchMethodNotAllowed - A route can be matched through the request path, but it cannot support the HTTP method used by the current request;
- RouteMatchUnknown — The program has not yet started matching, indicating the context is in its initial state.
If you call this method in middleware registered on the Slim instance through the Slim#Use method, the returned value is very likely to be RouteMatchUnknown, because at this point the program has not yet matched the route for the current request. Only when the request returns in reverse order might other values be obtained.
Refer to Quick Start to understand what middleware is.
func (*contextImpl) RouteInfo
func (c *contextImpl) RouteInfo() RouteInfo
Returns route information for the current request.
func (*contextImpl) PathParam
func (c *contextImpl) PathParam(name string) string
Gets the path parameter value with the specified name. Returns an empty string if it doesn't exist.
func (*contextImpl) PathParams
func (c *contextImpl) PathParams() PathParams
Returns all path parameters.
func (*contextImpl) SetPathParams
func (c *contextImpl) SetPathParams(params PathParams)
Sets path parameters during the current request lifecycle.
func (*contextImpl) QueryParam
func (c *contextImpl) QueryParam(name string) string
Returns the query parameter value with the specified name. Returns an empty string if it doesn't exist.
func (*contextImpl) QueryParams
func (c *contextImpl) QueryParams() url.Values
Returns all query parameters using the url.Values struct.
func (*contextImpl) QueryString
func (c *contextImpl) QueryString() string
Returns the query string.
func (*contextImpl) FormValue
func (c *contextImpl) FormValue(name string) string
Returns the form data with the specified name.
func (*contextImpl) FormParams()
func (c *contextImpl) FormParams() (url.Values, error)
Returns all submitted form data using the url.Values struct.
func (*contextImpl) FormFile(name string)
func (c *contextImpl) FormFile(name string) (*multipart.FileHeader, error)
Returns the uploaded file.
func (*contextImpl) Header
func (c *contextImpl) Header(key string) string
Returns the value of the request header with name key.
func (*contextImpl) SetHeader
func (c *contextImpl) SetHeader(key string, values ...string)
Sets response header.
func (*contextImpl) MultipartForm()
func (c *contextImpl) MultipartForm() (*multipart.Form, error)
Returns all uploaded files. The second return value indicates file parsing failure.
func (*contextImpl) Cookie(name string)
func (c *contextImpl) Cookie(name string) (*http.Cookie, error)
Returns the cookie with the specified name from the request.
func (*contextImpl) SetCookie
func (c *contextImpl) SetCookie(cookie *http.Cookie)
Adds a Set-Cookie header in the HTTP response.
func (*contextImpl) Cookies
func (c *contextImpl) Cookies() []*http.Cookie
Returns the HTTP cookies sent with the request.
func (*contextImpl) Get
func (c *contextImpl) Get(key string) any
Returns data stored in the context.
func (*contextImpl) Set
func (c *contextImpl) Set(key string, val any)
Saves a value to the context.
func (*contextImpl) Bind
func (c *contextImpl) Bind(i any) error
Binds data submitted during the request to parameter i, mainly from the following sources:
- Query parameters (Query String);
- Request body data (submitted through POST and other request methods);
- Matched route parameters;
- Submitted header values.
The request body is identified by the value of the Content-Type header, then different serializer Serializer are called to deserialize to parameter i.
func (*contextImpl) Validate
func (c *contextImpl) Validate(i any) error
Validates the provided i. Typically called after Context#Bind().
A validator must be registered with Slim#Validator.
func (*contextImpl) Written
func (c *contextImpl) Written() bool
Returns whether the context response has been written.
func (*contextImpl) Render
func (c *contextImpl) Render(code int, name string, data any) error
Renders a template with data and sends a text/html response with status code.
A renderer must be registered with Slim.Renderer.
func (*contextImpl) HTML
func (c *contextImpl) HTML(code int, html string) error
Sends an HTTP response with status code.
func (*contextImpl) HTMLBlob
func (c *contextImpl) HTMLBlob(code int, b []byte) error
Sends an HTTP blob response with status code.
func (*contextImpl) String
func (c *contextImpl) String(code int, s string) error
Sends a string response with status code.
func (*contextImpl) JSON
func (c *contextImpl) JSON(code int, i any) error
Sends a JSON response with status code.
func (*contextImpl) JSONPretty
func (c *contextImpl) JSONPretty(code int, i any, indent string) error
Sends a formatted JSON with status code.
func (*contextImpl) JSONBlob
func (c *contextImpl) JSONBlob(code int, b []byte) error
Sends a JSON blob response with status code.
func (*contextImpl) JSONP
func (c *contextImpl) JSONP(code int, callback string, i any) error
Sends a JSONP response with status code. It uses callback to construct the JSONP payload.
func (*contextImpl) JSONPBlob
func (c *contextImpl) JSONPBlob(code int, callback string, b []byte) error
Sends a JSONP blob response with status code. It uses callback to construct the JSONP payload.
func (*contextImpl) XML
func (c *contextImpl) XML(code int, i any) error
Sends an XML response with status code.
func (*contextImpl) XMLPretty
func (c *contextImpl) XMLPretty(code int, i any, indent string) error
Sends a formatted XML with status code.
func (*contextImpl) XMLBlob
func (c *contextImpl) XMLBlob(code int, b []byte) error
Sends an XML blob response with status code.
func (*contextImpl) Blob
func (c *contextImpl) Blob(code int, contentType string, b []byte) error
Sends a blob response with status code and content type.
func (*contextImpl) Stream
func (c *contextImpl) Stream(code int, contentType string, r io.Reader) error
Sends a streaming response with status code and content type.
func (*contextImpl) File
func (c *contextImpl) File(file string, filesystem ...fs.FS) error
Sends a response with file content.
func (*contextImpl) Attachment
func (c *contextImpl) Attachment(file string, name string) error
Sends a response as an attachment, prompting the client to save the file.
func (*contextImpl) Inline
func (c *contextImpl) Inline(file string, name string) error
Sends a response as inline, opening the file in the browser.
func (*contextImpl) NoContent
func (c *contextImpl) NoContent(code ...int) error
Sends a response without body and status code.
func (*contextImpl) Redirect
func (c *contextImpl) Redirect(code int, url string) error
Redirects the request to the provided URL with status code.
func (*contextImpl) Error
func (c *contextImpl) Error(err error)
Error invokes the registered HTTP error handler.
We should not use this method in route handler functions and middleware. Instead, return an error value, and the Slim program will call the error handler function we defined to handle errors uniformly.
func (*contextImpl) Slim
func (c *contextImpl) Slim() *Slim
Returns the Slim instance.