Documentation
¶
Overview ¶
Package air implements an ideally refined web framework for Go.
Router ¶
A router is basically the most important component of a web framework. In this framework, registering a route usually requires at least two params:
air.Default.GET(
"/users/:UserID/posts/:PostID/assets/*",
func(req *air.Request, res *air.Response) error {
userID, err := req.Param("UserID").Value().Int64()
if err != nil {
return err
}
postID, err := req.Param("PostID").Value().Int64()
if err != nil {
return err
}
assetPath := req.Param("*").Value().String()
return res.WriteJSON(map[string]interface{}{
"user_id": userID,
"post_id": postID,
"asset_path": assetPath,
})
},
)
The first param is a route path that contains 6 components. Among them, "users", "posts" and "assets" are static components, ":UserID" and ":PostID" are param components, "*" is an any param component. Note that all route params (param component(s) and any param component) will be parsed into the `Request` and can be accessed via the `Request.Param` and the `Request.Params`. The name of a `RequestParam` parsed from a param component always discards its leading ":", such as ":UserID" will become "UserID". The name of a `RequestParam` parsed from an any param component is "*".
The second param is a `Handler` that serves the requests that match this route.
Index ¶
- Variables
- func DefaultErrorHandler(err error, req *Request, res *Response)
- func DefaultMethodNotAllowedHandler(req *Request, res *Response) error
- func DefaultNotFoundHandler(req *Request, res *Response) error
- type Air
- func (a *Air) Addresses() []string
- func (a *Air) BATCH(methods []string, path string, h Handler, gases ...Gas)
- func (a *Air) CONNECT(path string, h Handler, gases ...Gas)
- func (a *Air) Close() error
- func (a *Air) DELETE(path string, h Handler, gases ...Gas)
- func (a *Air) FILE(path, filename string, gases ...Gas)
- func (a *Air) FILES(prefix, root string, gases ...Gas)
- func (a *Air) GET(path string, h Handler, gases ...Gas)
- func (a *Air) Group(prefix string, gases ...Gas) *Group
- func (a *Air) HEAD(path string, h Handler, gases ...Gas)
- func (a *Air) OPTIONS(path string, h Handler, gases ...Gas)
- func (a *Air) PATCH(path string, h Handler, gases ...Gas)
- func (a *Air) POST(path string, h Handler, gases ...Gas)
- func (a *Air) PUT(path string, h Handler, gases ...Gas)
- func (a *Air) Serve() error
- func (a *Air) Shutdown(ctx context.Context) error
- func (a *Air) TRACE(path string, h Handler, gases ...Gas)
- type Gas
- type Group
- func (g *Group) BATCH(methods []string, path string, h Handler, gases ...Gas)
- func (g *Group) CONNECT(path string, h Handler, gases ...Gas)
- func (g *Group) DELETE(path string, h Handler, gases ...Gas)
- func (g *Group) FILE(path, file string, gases ...Gas)
- func (g *Group) FILES(prefix, root string, gases ...Gas)
- func (g *Group) GET(path string, h Handler, gases ...Gas)
- func (g *Group) Group(prefix string, gases ...Gas) *Group
- func (g *Group) HEAD(path string, h Handler, gases ...Gas)
- func (g *Group) OPTIONS(path string, h Handler, gases ...Gas)
- func (g *Group) PATCH(path string, h Handler, gases ...Gas)
- func (g *Group) POST(path string, h Handler, gases ...Gas)
- func (g *Group) PUT(path string, h Handler, gases ...Gas)
- func (g *Group) TRACE(path string, h Handler, gases ...Gas)
- type Handler
- type Request
- func (r *Request) Bind(v interface{}) error
- func (r *Request) ClientAddress() string
- func (r *Request) Cookie(name string) *http.Cookie
- func (r *Request) Cookies() []*http.Cookie
- func (r *Request) HTTPRequest() *http.Request
- func (r *Request) LocalizedString(key string) string
- func (r *Request) Param(name string) *RequestParam
- func (r *Request) Params() []*RequestParam
- func (r *Request) RemoteAddress() string
- func (r *Request) SetHTTPRequest(hr *http.Request)
- func (r *Request) SetValue(key string, value interface{})
- func (r *Request) Value(key string) interface{}
- func (r *Request) Values() map[string]interface{}
- type RequestParam
- type RequestParamValue
- func (rpv *RequestParamValue) Bool() (bool, error)
- func (rpv *RequestParamValue) File() (*multipart.FileHeader, error)
- func (rpv *RequestParamValue) Float32() (float32, error)
- func (rpv *RequestParamValue) Float64() (float64, error)
- func (rpv *RequestParamValue) Int() (int, error)
- func (rpv *RequestParamValue) Int8() (int8, error)
- func (rpv *RequestParamValue) Int16() (int16, error)
- func (rpv *RequestParamValue) Int32() (int32, error)
- func (rpv *RequestParamValue) Int64() (int64, error)
- func (rpv *RequestParamValue) String() string
- func (rpv *RequestParamValue) Uint() (uint, error)
- func (rpv *RequestParamValue) Uint8() (uint8, error)
- func (rpv *RequestParamValue) Uint16() (uint16, error)
- func (rpv *RequestParamValue) Uint32() (uint32, error)
- func (rpv *RequestParamValue) Uint64() (uint64, error)
- type Response
- func (r *Response) Defer(f func())
- func (r *Response) HTTPResponseWriter() http.ResponseWriter
- func (r *Response) ProxyPass(target string, rpm *ReverseProxyModifier) error
- func (r *Response) Push(target string, pos *http.PushOptions) error
- func (r *Response) Redirect(url string) error
- func (r *Response) Render(m map[string]interface{}, templates ...string) error
- func (r *Response) SetCookie(c *http.Cookie)
- func (r *Response) SetHTTPResponseWriter(hrw http.ResponseWriter)
- func (r *Response) WebSocket() (*WebSocket, error)
- func (r *Response) Write(content io.ReadSeeker) error
- func (r *Response) WriteFile(filename string) error
- func (r *Response) WriteHTML(h string) error
- func (r *Response) WriteJSON(v interface{}) error
- func (r *Response) WriteMsgpack(v interface{}) error
- func (r *Response) WriteProtobuf(v interface{}) error
- func (r *Response) WriteString(s string) error
- func (r *Response) WriteTOML(v interface{}) error
- func (r *Response) WriteXML(v interface{}) error
- func (r *Response) WriteYAML(v interface{}) error
- type ReverseProxyModifier
- type WebSocket
- func (ws *WebSocket) Close() error
- func (ws *WebSocket) Listen()
- func (ws *WebSocket) SetMaxMessageBytes(mmb int64)
- func (ws *WebSocket) SetReadDeadline(t time.Time) error
- func (ws *WebSocket) SetWriteDeadline(t time.Time) error
- func (ws *WebSocket) WriteBinary(b []byte) error
- func (ws *WebSocket) WriteConnectionClose(status int, reason string) error
- func (ws *WebSocket) WritePing(appData string) error
- func (ws *WebSocket) WritePong(appData string) error
- func (ws *WebSocket) WriteText(text string) error
Constants ¶
This section is empty.
Variables ¶
var Default = New()
Default is the default instance of the `Air`.
If you only need one instance of the `Air`, then you should use the `Default`. Unless you think you can efficiently pass your instance in different scopes.
Functions ¶
func DefaultErrorHandler ¶
DefaultErrorHandler is the default centralized error handler for the server.
func DefaultMethodNotAllowedHandler ¶
DefaultMethodNotAllowedHandler is the default `Handler` that returns method not allowed error.
func DefaultNotFoundHandler ¶
DefaultNotFoundHandler is the default `Handler` that returns not found error.
Types ¶
type Air ¶
type Air struct {
// AppName is the name of the current web application.
//
// It is recommended to set a name and try to ensure that the name is
// unique (used to distinguish between different web applications).
//
// Default value: "air"
AppName string `mapstructure:"app_name"`
// MaintainerEmail is the e-mail address of the one who is responsible
// for maintaining the current web application.
//
// It is recommended to set an e-mail if the ACME feature of the current
// web application is enabled (used by the CAs, such as Let's Encrypt,
// to notify about problems with issued certificates).
//
// Default value: ""
MaintainerEmail string `mapstructure:"maintainer_email"`
// DebugMode indicates whether the current web application is in debug
// mode.
//
// Please keep in mind that the debug mode is quite bossy, some features
// of the current web application will be affected in the debug mode. So
// never use the debug mode in a production environment unless you want
// to do something crazy.
//
// Default value: false
DebugMode bool `mapstructure:"debug_mode"`
// Address is the TCP address that the server of the current web
// application listens on.
//
// There is always an address here that contains a free port.
//
// If the port of the `Address` is "0", a port is automatically chosen.
// The `Addresses` can be used to discover the chosen port.
//
// Default value: ":8080"
Address string `mapstructure:"address"`
// ReadTimeout is the maximum duration the server of the current web
// application reads a request entirely, including the body part.
//
// The `ReadTimeout` does not let the handlers make per-request
// decisions on each request body's acceptable deadline or upload rate.
//
// Default value: 0
ReadTimeout time.Duration `mapstructure:"read_timeout"`
// ReadHeaderTimeout is the amount of time allowed the server of the
// current web application reads the headers of a request.
//
// The connection's read deadline is reset after reading the headers and
// the handler can decide what is considered too slow for the body.
//
// Default value: 0
ReadHeaderTimeout time.Duration `mapstructure:"read_header_timeout"`
// WriteTimeout is the maximum duration the server of the current web
// application writes a response.
//
// The `WriteTimeout` is reset whenever a new request's header is read.
// Like the `ReadTimeout`, the `WriteTimeout` does not let handlers make
// decisions on a per-request basis.
//
// Default value: 0
WriteTimeout time.Duration `mapstructure:"write_timeout"`
// IdleTimeout is the maximum amount of time the server of the current
// web application waits for the next request.
//
// If the `IdleTimeout` is zero, the value of the `ReadTimeout` is used.
// If both are zero, the value of the `ReadHeaderTimeout` is used.
//
// Default value: 0
IdleTimeout time.Duration `mapstructure:"idle_timeout"`
// MaxHeaderBytes is the maximum number of bytes the server of the
// current web application will read parsing the request header's names
// and values, including the request line.
//
// Default value: 1048576
MaxHeaderBytes int `mapstructure:"max_header_bytes"`
// TLSCertFile is the path to the TLS certificate file used when
// starting the server of the current web application.
//
// If the certificate is signed by a certificate authority, the TLS
// certificate file should be the concatenation of the certificate, any
// intermediates, and the CA's certificate.
//
// The `TLSCertFile` must be set at the same time as the `TLSKeyFile` to
// make the server of the current web application to handle requests on
// incoming TLS connections.
//
// Default value: ""
TLSCertFile string `mapstructure:"tls_cert_file"`
// TLSKeyFile is the path to the TLS key file used when starting the
// server of the current web application.
//
// The key must match the certificate targeted by the `TLSCertFile`.
//
// The `TLSKeyFile` must be set at the same time as the `TLSCertFile` to
// make the server of the current web application to handle requests on
// incoming TLS connections.
//
// Default value: ""
TLSKeyFile string `mapstructure:"tls_key_file"`
// ACMEEnabled indicates whether the ACME feature of the current web
// application is enabled.
//
// The `ACMEEnabled` gives the server of the current web application the
// ability to automatically retrieve new TLS certificates from the ACME
// CA targeted by the `ACMEDirectoryURL`.
//
// The `ACMEEnabled` only works when the `DebugMode` is false and both
// the `TLSCertFile` and the `TLSKeyFile` are empty.
//
// Default value: false
ACMEEnabled bool `mapstructure:"acme_enabled"`
// ACMEDirectoryURL is the CA directory URL of the ACME feature of the
// current web application.
//
// The CA directory must be trusted because the ACME will automatically
// accept the Terms of Service (TOS) prompted from it.
//
// Default value: "https://acme-v01.api.letsencrypt.org/directory"
ACMEDirectoryURL string `mapstructure:"acme_directory_url"`
// ACMECertRoot is the root of the certificates of the ACME feature of
// the current web application.
//
// It is recommended to set a persistent root since all CAs have a rate
// limit on issuing certificates. Different web applications can share
// the same place (if they are all built using this framework).
//
// Default value: "acme-certs"
ACMECertRoot string `mapstructure:"acme_cert_root"`
// ACMEHostWhitelist is the list of hosts allowed by the ACME feature of
// the current web application.
//
// It is highly recommended to set a list of hosts. If the length of the
// list is not zero, then all connections that are not connected to the
// hosts in the list will not be able to obtain new TLS certificates
// from the ACME CA targeted by the `ACMEDirectoryURL`.
//
// Default value: nil
ACMEHostWhitelist []string `mapstructure:"acme_host_whitelist"`
// HTTPSEnforced indicates whether the current web application is
// forcibly accessible only via the HTTPS scheme (HTTP requests will
// automatically redirect to HTTPS).
//
// The `HTTPSEnforced` only works when the server of the current web
// application can handle requests on incoming TLS connections.
//
// The `HTTPSEnforced` will be forced to true when the `ACMEEnabled` is
// true, the `DebugMode` is false and both the `TLSCertFile` and the
// `TLSKeyFile` are empty.
//
// Default value: false
HTTPSEnforced bool `mapstructure:"https_enforced"`
// HTTPSEnforcedPort is the port of the TCP address (share the same host
// as the `Address`) that the server of the current web application
// listens on. All requests to this port will be forced to redirect to
// HTTPS.
//
// If the `HTTPSEnforcedPort` is "0", a port is automatically chosen.
// The `Addresses` can be used to discover the chosen port.
//
// Default value: "80"
HTTPSEnforcedPort string `mapstructure:"https_enforced_port"`
// WebSocketHandshakeTimeout is the maximum amount of time the server of
// the current web application waits for a WebSocket handshake to
// complete.
//
// Default value: 0
WebSocketHandshakeTimeout time.Duration `mapstructure:"websocket_handshake_timeout"`
// WebSocketSubprotocols is the list of supported WebSocket subprotocols
// of the server of the current web application.
//
// If the length of the list is not zero, then the `Response.WebSocket`
// negotiates a subprotocol by selecting the first match in the list
// with a protocol requested by the client. If there is no match, then
// no protocol is negotiated (the Sec-Websocket-Protocol header is not
// included in the handshake response).
//
// Default value: nil
WebSocketSubprotocols []string `mapstructure:"websocket_subprotocols"`
// PROXYProtocolEnabled indicates whether the PROXY protocol feature of
// the current web application is enabled.
//
// The `PROXYProtocolEnabled` gives the server of the current web
// application the ability to support the PROXY protocol (See
// https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt).
//
// Default value: false
PROXYProtocolEnabled bool `mapstructure:"proxy_protocol_enabled"`
// PROXYProtocolReadHeaderTimeout is the amount of time allowed the
// PROXY protocol feature of the current web application reads the
// PROXY protocol header of a connection.
//
// The connection's read deadline is reset after reading the PROXY
// protocol header.
//
// Default value: 0
PROXYProtocolReadHeaderTimeout time.Duration `mapstructure:"proxy_protocol_read_header_timeout"`
// PROXYProtocolRelayerIPWhitelist is the list of IP addresses or CIDR
// notation IP address ranges of the relayers allowed by the PROXY
// protocol feature of the current web application.
//
// It is highly recommended to set a list of IP addresses or CIDR
// notation IP address ranges. If the length of the list is not zero,
// then all connections relayed from the IP addresses are not in the
// list will not be able to act the PROXY protocol.
//
// Default value: nil
PROXYProtocolRelayerIPWhitelist []string `mapstructure:"proxy_protocol_relayer_ip_whitelist"`
// Pregases is the `Gas` chain stack of the current web application
// that performs before routing.
//
// The stack is always FILO.
//
// Default value: nil
Pregases []Gas `mapstructure:"-"`
// Gases is the `Gas` chain stack of the current web application that
// performs after routing.
//
// The stack is always FILO.
//
// Default value: nil
Gases []Gas `mapstructure:"-"`
// NotFoundHandler is the `Handler` of the current web application that
// returns not found error.
//
// The `NotFoundHandler` is never nil because the router of the current
// web application will use it as the default `Handler` when no matching
// routes are found.
//
// Default value: `DefaultNotFoundHandler`
NotFoundHandler func(*Request, *Response) error `mapstructure:"-"`
// MethodNotAllowedHandler is the `Handler` of the current web
// application that returns method not allowed error.
//
// The `MethodNotAllowedHandler` is never nil because the router of the
// current web application will use it as the default `Handler` when it
// finds a matching route but its method is not registered.
//
// Default value: `DefaultMethodNotAllowedHandler`
MethodNotAllowedHandler func(*Request, *Response) error `mapstructure:"-"`
// ErrorHandler is the centralized error handler of the server of the
// current web application.
//
// The `ErrorHandler` is never nil because it is used in every
// request-response cycle that has an error.
//
// Default value: `DefaultErrorHandler`
ErrorHandler func(error, *Request, *Response) `mapstructure:"-"`
// ErrorLogger is the `log.Logger` that logs errors that occur in the
// server of the current web application.
//
// If the `ErrorLogger` is nil, logging is done via the log package's
// standard logger.
//
// Default value: nil
ErrorLogger *log.Logger `mapstructure:"-"`
// AutoPushEnabled indicates whether the HTTP/2 server push automatic
// mechanism feature of the current web application is enabled.
//
// The `AutoPushEnabled` gives the `Response.WriteHTML` the ability to
// automatically analyze the response content and use the
// `Response.Push` to push the appropriate resources to the client.
//
// The `AutoPushEnabled` only works when the protocol version of the
// request is HTTP/2.
//
// Default value: false
AutoPushEnabled bool `mapstructure:"auto_push_enabled"`
// MinifierEnabled indicates whether the minifier feature of the current
// web application is enabled.
//
// The `MinifierEnabled` gives the `Response.Write` the ability to
// minify the matching response content on the fly based on the
// Content-Type header.
//
// Default value: false
MinifierEnabled bool `mapstructure:"minifier_enabled"`
// MinifierMIMETypes is the list of MIME types of the minifier feature
// of the current web application that will trigger the minimization.
//
// Supported MIME types:
// * text/html
// * text/css
// * application/javascript
// * application/json
// * application/xml
// * image/svg+xml
//
// Unsupported MIME types will be silently ignored.
//
// Default value: ["text/html", "text/css", "application/javascript",
// "application/json", "application/xml", "image/svg+xml"]
MinifierMIMETypes []string `mapstructure:"minifier_mime_types"`
// GzipEnabled indicates whether the gzip feature of the current web
// application is enabled.
//
// The `GzipEnabled` gives the `Response` the ability to gzip the
// matching response content on the fly based on the Content-Type
// header.
//
// Default value: false
GzipEnabled bool `mapstructure:"gzip_enabled"`
// GzipMinContentLength is the minimum content length of the gzip
// featrue of the current web application used to limit at least how
// much response content can be gzipped.
//
// The content length is determined only from the Content-Length header.
//
// Default value: 1024
GzipMinContentLength int64 `mapstructure:"gzip_min_content_length"`
// GzipMIMETypes is the list of MIME types of the gzip feature of the
// current web application that will trigger the gzip.
//
// Default value: ["text/plain", "text/html", "text/css",
// "application/javascript", "application/json", "application/xml",
// "application/toml", "application/yaml", "image/svg+xml"]
GzipMIMETypes []string `mapstructure:"gzip_mime_types"`
// GzipCompressionLevel is the compression level of the gzip feature of
// the current web application.
//
// Default value: `gzip.DefaultCompression`
GzipCompressionLevel int `mapstructure:"gzip_compression_level"`
// GzipFlushThreshold is the flush threshold of the gzip feature of the
// current web application.
//
// Once the pending compressed data in the gzip writer reach the flush
// threshold, they will be flushed into the underlying writer of the
// gzip writer immediately.
//
// The `GzipFlushThreshold` only works when it is greater than zero.
//
// Default value: 8192
GzipFlushThreshold int `mapstructure:"gzip_flush_threshold"`
// RendererTemplateRoot is the root of the HTML templates of the
// renderer feature of the current web application.
//
// All HTML template files inside the root will be recursively parsed
// into the renderer.
//
// Default value: "templates"
RendererTemplateRoot string `mapstructure:"renderer_template_root"`
// RendererTemplateExts is the list of filename extensions of the HTML
// templates of the renderer feature of the current web application used
// to distinguish the HTML template files in the `RendererTemplateRoot`
// when parsing them into the renderer.
//
// Default value: [".html"]
RendererTemplateExts []string `mapstructure:"renderer_template_exts"`
// RendererTemplateLeftDelim is the left side of the HTML template
// delimiter of the renderer feature of the current web application.
//
// default value: "{{"
RendererTemplateLeftDelim string `mapstructure:"renderer_template_left_delim"`
// RendererTemplateRightDelim is the right side of the HTML template
// delimiter of the renderer feature of the current web application.
//
// Default value: "}}"
RendererTemplateRightDelim string `mapstructure:"renderer_template_right_delim"`
// RendererTemplateFuncMap is the HTML template function map of the
// renderer feature of the current web application.
//
// Default value: nil
RendererTemplateFuncMap template.FuncMap `mapstructure:"-"`
// CofferEnabled indicates whether the coffer feature of the current web
// application is enabled.
//
// The `CofferEnabled` gives the `Response.WriteFile` the ability to use
// the runtime memory to reduce the disk I/O pressure.
//
// Default value: false
CofferEnabled bool `mapstructure:"coffer_enabled"`
// CofferMaxMemoryBytes is the maximum number of bytes of the runtime
// memory the coffer feature of the current web application will use.
//
// Default value: 33554432
CofferMaxMemoryBytes int `mapstructure:"coffer_max_memory_bytes"`
// CofferAssetRoot is the root of the assets of the coffer feature of
// the current web application.
//
// All asset files inside the root will be recursively parsed into the
// coffer.
//
// Default value: "assets"
CofferAssetRoot string `mapstructure:"coffer_asset_root"`
// CofferAssetExts is the list of filename extensions of the assets of
// the coffer feature of the current web application used to distinguish
// the asset files in the `CofferAssetRoot` when loading them into the
// coffer.
//
// Default value: [".html", ".css", ".js", ".json", ".xml", ".toml",
// ".yaml", ".yml", ".svg", ".jpg", ".jpeg", ".png", ".gif"]
CofferAssetExts []string `mapstructure:"coffer_asset_exts"`
// I18nEnabled indicates whether the i18n feature of the current web
// application is enabled.
//
// The `I18nEnabled` gives the `Request.LocalizedString` and the
// `Response.Render` the ability to adapt to the request's favorite
// conventions based on the Accept-Language header.
//
// Default value: false
I18nEnabled bool `mapstructure:"i18n_enabled"`
// I18nLocaleRoot is the root of the locales of the i18n feature of the
// current web application.
//
// All TOML-based locale files (".toml" is the extension) inside the
// root will be parsed into the i18n and their names (without extension)
// will be used as locales.
//
// Default value: "locales"
I18nLocaleRoot string `mapstructure:"i18n_locale_root"`
// I18nLocaleBase is the base of the locales of the i18n feature of the
// current web application used when a locale cannot be found.
//
// Default value: "en-US"
I18nLocaleBase string `mapstructure:"i18n_locale_base"`
// ConfigFile is the path to the configuration file that will be parsed
// into the matching fields of the current web application before
// starting the server.
//
// The ".json" extension means the configuration file is JSON-based.
//
// The ".toml" extension means the configuration file is TOML-based.
//
// The ".yaml" and the ".yml" extensions means the configuration file is
// YAML-based.
//
// Default value: ""
ConfigFile string `mapstructure:"-"`
// contains filtered or unexported fields
}
Air is the top-level struct of this framework.
It is highly recommended not to modify the value of any field of the `Air` after calling the `Air.Serve`, which will cause unpredictable problems.
The new instances of the `Air` should only be created by calling the `New`. If you only need one instance of the `Air`, then it is recommended to use the `Default`, which will help you simplify the scope management.
func New ¶
func New() *Air
New returns a new instance of the `Air` with default field values.
The `New` is the only function that creates new instances of the `Air` and keeps everything working.
func (*Air) Addresses ¶ added in v0.12.1
Addresses returns all TCP addresses that the server of the a actually listens on.
func (*Air) BATCH ¶
BATCH registers a batch of routes for the methods and the path with the matching h in the router of the a with the optional route-level gases.
The methods must either be nil (means all) or consists of one or more of the "GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "CONNECT", "OPTIONS" and "TRACE". Invalid methods will be silently ignored.
The path may consist of static component(s), param component(s) and any param component.
The gases is always FILO.
func (*Air) CONNECT ¶
CONNECT registers a new CONNECT route for the path with the matching h in the router of the a with the optional route-level gases.
The path may consist of static component(s), param component(s) and any param component.
The gases is always FILO.
func (*Air) DELETE ¶
DELETE registers a new DELETE route for the path with the matching h in the router of the a with the optional route-level gases.
The path may consist of static component(s), param component(s) and any param component.
The gases is always FILO.
func (*Air) FILE ¶
FILE registers a new GET route and a new HEAD route with the path in the router of the a to serve a static file with the filename and the optional route-level gases.
The path may consist of static component(s), param component(s) and any param component.
The gases is always FILO.
func (*Air) FILES ¶ added in v0.5.0
FILES registers a new GET route and a new HEAD route with the path prefix in the router of the a to serve the static files from the root with the optional route-level gases.
The path prefix may consits of static component(s) and param component(s). But it must not contain an any param component.
The gases is always FILO.
func (*Air) GET ¶
GET registers a new GET route for the path with the matching h in the router of the a with the optional route-level gases.
The path may consist of static component(s), param component(s) and any param component.
The gases is always FILO.
func (*Air) Group ¶
Group returns a new instance of the `Group` with the path prefix and the optional group-level gases that inherited from the a.
The path prefix may consits of static component(s) and param component(s). But it must not contain an any param component.
The gases is always FILO.
func (*Air) HEAD ¶
HEAD registers a new HEAD route for the path with the matching h in the router of the a with the optional route-level gases.
The path may consist of static component(s), param component(s) and any param component.
The way, the gases is always FILO.
func (*Air) OPTIONS ¶
OPTIONS registers a new OPTIONS route for the path with the matching h in the router of the a with the optional route-level gases.
The path may consist of static component(s), param component(s) and any param component.
The gases is always FILO.
func (*Air) PATCH ¶
PATCH registers a new PATCH route for the path with the matching h in the router of the a with the optional route-level gases.
The path may consist of static component(s), param component(s) and any param component.
The gases is always FILO.
func (*Air) POST ¶
POST registers a new POST route for the path with the matching h in the router of the a with the optional route-level gases.
The path may consist of static component(s), param component(s) and any param component.
The gases is always FILO.
func (*Air) PUT ¶
PUT registers a new PUT route for the path with the matching h in the router of the a with the optional route-level gases.
The path may consist of static component(s), param component(s) and any param component.
The gases is always FILO.
func (*Air) Shutdown ¶
Shutdown gracefully shuts down the server of the a without interrupting any active connections. It works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the ctx expires before the shutdown is complete, it returns the context's error, otherwise it returns any error returned from closing the underlying listener(s) of the server of the a.
When the `Shutdown` is called, the `Serve` immediately return the `http.ErrServerClosed`. Make sure the program does not exit and waits instead for the `Shutdown` to return.
The `Shutdown` does not attempt to close nor wait for hijacked connections such as WebSockets. The caller should separately notify such long-lived connections of shutdown and wait for them to close, if desired.
type Gas ¶
Gas defines a function to process gases.
A gas is a function chained in the request-response cycle with access to the `Request` and the `Response` which it uses to perform a specific action, for example, logging every request or recovering from panics.
The argument is the next `Handler` that the gas will be called.
The return value is the gas that is wrapped into a `Handler`.
type Group ¶
type Group struct {
// Air is where the current group belong.
Air *Air
// Prefix is the prefix of all route paths of the current group.
//
// All paths of routes registered by the current group will share the
// same prefix.
//
// The path prefix may consits of static component(s) and param
// component(s). But it must not contain an any param component.
Prefix string
// Gases is the group-level gases of the current group.
//
// All gases of routes registered by the current group will share the
// same group-level gases at the bottom of the stack.
//
// The gases is always FILO.
Gases []Gas
}
Group is a set of sub-routes for a specified route. It can be used for inner routes that share common gases or functionality that should be separate from the parent while still inheriting from it.
type Handler ¶
Handler defines a function to serve requests.
func WrapHTTPHandler ¶ added in v0.8.4
WrapHTTPHandler provides a convenient way to wrap an `http.Handler` into a `Handler`.
type Request ¶
type Request struct {
// Air is where the current request belong.
Air *Air
// Method is the method of the current request.
//
// See RFC 7231, section 4.3.
//
// For HTTP/1.x, it is from the request-line.
//
// For HTTP/2, it is from the ":method" pseudo-header.
//
// E.g.: "GET"
Method string
// Scheme is the scheme of the current request, it is "http" or "https".
//
// See RFC 3986, section 3.1.
//
// For HTTP/1.x, it is from the request-line.
//
// For HTTP/2, it is from the ":scheme" pseudo-header.
//
// E.g.: "http"
Scheme string
// Authority is the authority of the current request. It may be of the
// form "host:port".
//
// See RFC 3986, Section 3.2.
//
// For HTTP/1.x, it is from the Host header.
//
// For HTTP/2, it is from the ":authority" pseudo-header.
//
// E.g.: "localhost:8080"
Authority string
// Path is the path of the current request. Note that it contains the
// query part (anyway, the HTTP/2 specification says so).
//
// For HTTP/1.x, it represents the request-target of the request-line.
// See RFC 7230, section 3.1.1.
//
// For HTTP/2, it represents the ":path" pseudo-header. See RFC 7540,
// section 8.1.2.3.
//
// E.g.: "/foo/bar?foo=bar"
Path string
// Header is the header map of the current request.
//
// The values of the Trailer header are the names of the trailers which
// will come later. In this case, those names of the header map will be
// set after reading from the `Body` returns the `io.EOF`.
//
// See RFC 7231, section 5.
//
// The `Header` is basically the same for both HTTP/1.x and HTTP/2. The
// only difference is that HTTP/2 requires header names to be lowercase
// (for aesthetic reasons, this framework decided to follow this rule
// implicitly, so please use the header name in the HTTP/1.x way). See
// RFC 7540, section 8.1.2.
//
// E.g.: {"Foo": ["bar"]}
Header http.Header
// Body is the message body of the current request.
Body io.Reader
// ContentLength records the length of the associated content. The value
// -1 indicates that the length is unknown (it will be set after reading
// from the `Body` returns the `io.EOF`). Values >= 0 indicate that the
// given number of bytes may be read from the `Body`.
ContentLength int64
// Context is the context that associated with the current request.
//
// The `Context` is canceled when the client's connection closes, the
// current request is canceled (with HTTP/2), or when the current
// request-response cycle is finished.
Context context.Context
// contains filtered or unexported fields
}
Request is an HTTP request.
The `Request` not only represents HTTP/1.x requests, but also represents HTTP/2 requests, and always acts as HTTP/2 requests.
func (*Request) Bind ¶
Bind binds the r into the v based on the Content-Type header.
Supported MIME types:
- application/json
- application/xml
- application/protobuf
- application/msgpack
- application/toml
- application/yaml
- application/x-www-form-urlencoded
- multipart/form-data
func (*Request) ClientAddress ¶
ClientAddress returns the original network address that sent the r.
Usually, the original network address is the same as the last network address that sent the r. But, the Forwarded header and the X-Forwarded-For header will be considered, which may affect the return value.
func (*Request) Cookie ¶
Cookie returns the matched `http.Cookie` for the name. It returns nil if not found.
func (*Request) HTTPRequest ¶
HTTPRequest returns the underlying `http.Request` of the r.
ATTENTION: You should never call this method unless you know what you are doing. And, be sure to call the `SetHTTPRequest` of the r when you have modified it.
func (*Request) LocalizedString ¶
LocalizedString returns localized string for the key based on the Accept-Language header. It returns the key without any changes if the `I18nEnabled` of the `Air` of the r is false or something goes wrong.
func (*Request) Param ¶
func (r *Request) Param(name string) *RequestParam
Param returns the matched `RequestParam` for the name. It returns nil if not found.
func (*Request) Params ¶
func (r *Request) Params() []*RequestParam
Params returns all `RequestParam` in the r.
func (*Request) RemoteAddress ¶
RemoteAddress returns the last network address that sent the r.
func (*Request) SetHTTPRequest ¶
SetHTTPRequest sets the hr to the underlying `http.Request` of the r.
ATTENTION: You should never call this method unless you know what you are doing.
func (*Request) SetValue ¶ added in v0.11.1
SetValue sets the matched `interface{}` for the key from the values associated with the r to the value.
type RequestParam ¶
type RequestParam struct {
// Name is the name of the current request param.
Name string
// Values is the values of the current request param.
//
// Access order: route param value (always at the first) > request query
// value(s) > request form value(s) > request multipart form value(s) >
// request multipart form file(s).
Values []*RequestParamValue
}
RequestParam is an HTTP request param.
The param may come from the route params, the request query, the request form, the request multipart form.
func (*RequestParam) Value ¶
func (rp *RequestParam) Value() *RequestParamValue
Value returns the first value of the rp. It returns nil if the rp is nil or there are no values.
Note that route params always have values.
type RequestParamValue ¶
type RequestParamValue struct {
// contains filtered or unexported fields
}
RequestParamValue is an HTTP request param value.
It may represent a route param value, a request query value, a request form value, a request multipart form value or a request multipart form file value.
func (*RequestParamValue) Bool ¶
func (rpv *RequestParamValue) Bool() (bool, error)
Bool returns a `bool` from the underlying value of the rpv.
func (*RequestParamValue) File ¶
func (rpv *RequestParamValue) File() (*multipart.FileHeader, error)
File returns a `multipart.FileHeader` from the underlying value of the rpv.
func (*RequestParamValue) Float32 ¶
func (rpv *RequestParamValue) Float32() (float32, error)
Float32 returns a `float32` from the underlying value of the rpv.
func (*RequestParamValue) Float64 ¶
func (rpv *RequestParamValue) Float64() (float64, error)
Float64 returns a `float64` from the underlying value of the rpv.
func (*RequestParamValue) Int ¶
func (rpv *RequestParamValue) Int() (int, error)
Int returns an `int` from the underlying value of the rpv.
func (*RequestParamValue) Int8 ¶
func (rpv *RequestParamValue) Int8() (int8, error)
Int8 returns an `int8` from the underlying value of the rpv.
func (*RequestParamValue) Int16 ¶
func (rpv *RequestParamValue) Int16() (int16, error)
Int16 returns an `int16` from the underlying value of the rpv.
func (*RequestParamValue) Int32 ¶
func (rpv *RequestParamValue) Int32() (int32, error)
Int32 returns an `int32` from the underlying value of the rpv.
func (*RequestParamValue) Int64 ¶
func (rpv *RequestParamValue) Int64() (int64, error)
Int64 returns an `int64` from the underlying value of the rpv.
func (*RequestParamValue) String ¶
func (rpv *RequestParamValue) String() string
String returns a `string` from the underlying value of the rpv. It returns "" if the rpv is not text-based.
func (*RequestParamValue) Uint ¶
func (rpv *RequestParamValue) Uint() (uint, error)
Uint returns an `uint` from the underlying value of the rpv.
func (*RequestParamValue) Uint8 ¶
func (rpv *RequestParamValue) Uint8() (uint8, error)
Uint8 returns an `uint8` from the underlying value of the rpv.
func (*RequestParamValue) Uint16 ¶
func (rpv *RequestParamValue) Uint16() (uint16, error)
Uint16 returns an `uint16` from the underlying value of the rpv.
func (*RequestParamValue) Uint32 ¶
func (rpv *RequestParamValue) Uint32() (uint32, error)
Uint32 returns an `uint32` from the underlying value of the rpv.
func (*RequestParamValue) Uint64 ¶
func (rpv *RequestParamValue) Uint64() (uint64, error)
Uint64 returns an `uint64` from the underlying value of the rpv.
type Response ¶
type Response struct {
// Air is where the current response belong.
Air *Air
// Status is the status code giving the result of the attempt to
// understand and satisfy the request.
//
// See RFC 7231, section 6.
//
// For HTTP/1.x, it will be put in the response-line.
//
// For HTTP/2, it will be the ":status" pseudo-header.
//
// E.g.: 200
Status int
// Header is the header map of the current response.
//
// By setting the Trailer header to the names of the trailers which will
// come later. In this case, those names of the header map are treated
// as if they were trailers.
//
// See RFC 7231, section 7.
//
// The `Header` is basically the same for both HTTP/1.x and HTTP/2. The
// only difference is that HTTP/2 requires header names to be lowercase
// (for aesthetic reasons, this framework decided to follow this rule
// implicitly, so please use the header name in the HTTP/1.x way). See
// RFC 7540, section 8.1.2.
//
// E.g.: {"Foo": ["bar"]}
Header http.Header
// Body is the message body of the current response. It can be used to
// write a streaming response.
Body io.Writer
// ContentLength records the length of the associated content. The value
// -1 indicates that the length is unknown (it will continue to increase
// as the data written to the `Body` increases). Values >= 0 indicate
// that the given number of bytes has been written to the `Body`.
ContentLength int64
// Written indicates whether the current response has been written.
Written bool
// Minified indicates whether the message body of the current response
// has been minifed.
Minified bool
// Gzipped indicates whether the message body of the current response
// has been gzipped.
Gzipped bool
// contains filtered or unexported fields
}
Response is an HTTP response.
The `Response` not only represents HTTP/1.x responses, but also represents HTTP/2 responses, and always acts as HTTP/2 responses.
func (*Response) Defer ¶
func (r *Response) Defer(f func())
Defer pushes the f onto the stack of functions that will be called after responding. Nil functions will be silently dropped.
func (*Response) HTTPResponseWriter ¶
func (r *Response) HTTPResponseWriter() http.ResponseWriter
HTTPResponseWriter returns the underlying `http.ResponseWriter` of the r.
ATTENTION: You should never call this method unless you know what you are doing. And, be sure to call the `SetHTTPResponseWriter` of the r when you have modified it.
func (*Response) ProxyPass ¶
func (r *Response) ProxyPass(target string, rpm *ReverseProxyModifier) error
ProxyPass passes the request to the target and writes the response from the target to the client by using the reverse proxy technique. If the rpm is non-nil, then it will be used to modify the request to the target and the response from the target.
The target must be based on the HTTP protocol (such as HTTP(S), WebSocket and gRPC). So, the scheme of the target must be "http", "https", "ws", "wss", "grpc" or "grpcs".
func (*Response) Push ¶
func (r *Response) Push(target string, pos *http.PushOptions) error
Push initiates an HTTP/2 server push. This constructs a synthetic request using the target and the pos, serializes that request into a "PUSH_PROMISE" frame, then dispatches that request using the server's request handler. If pos is nil, default options are used.
The target must either be an absolute path (like "/path") or an absolute URL that contains a valid authority and the same scheme as the parent request. If the target is a path, it will inherit the scheme and authority of the parent request.
It returns `http.ErrNotSupported` if the client has disabled push or if push is not supported on the underlying connection.
func (*Response) Redirect ¶
Redirect writes the url as a redirection to the client. Note that the `Status` of the r will be the `http.StatusFound` if it is not a redirection status.
func (*Response) Render ¶
Render renders one or more HTML templates with the m and writes the results as a "text/html" content to the client. The results rendered by the former can be inherited by accessing the `m["InheritedHTML"]`.
func (*Response) SetCookie ¶
SetCookie sets the c to the `Header` of the r. Invalid cookies will be silently dropped.
func (*Response) SetHTTPResponseWriter ¶
func (r *Response) SetHTTPResponseWriter(hrw http.ResponseWriter)
SetHTTPResponseWriter sets the hrw to the underlying `http.ResponseWriter` of the r.
ATTENTION: You should never call this method unless you know what you are doing.
func (*Response) WebSocket ¶
WebSocket switches the connection of the r to the WebSocket protocol. See RFC 6455.
func (*Response) Write ¶
func (r *Response) Write(content io.ReadSeeker) error
Write writes the content to the client.
The main benefit of the `Write` over the `io.Copy` with the `Body` of the r is that it handles range requests properly, sets the Content-Type header, and handles the If-Match header, the If-Unmodified-Since header, the If-None-Match header, the If-Modified-Since header and the If-Range header of the requests.
func (*Response) WriteFile ¶
WriteFile writes a file content targeted by the filename to the client.
func (*Response) WriteJSON ¶
WriteJSON writes an "application/json" content encoded from the v to the client.
func (*Response) WriteMsgpack ¶
WriteMsgpack writes an "application/msgpack" content encoded from the v to the client.
func (*Response) WriteProtobuf ¶
WriteProtobuf writes an "application/protobuf" content encoded from the v to the client.
func (*Response) WriteString ¶
WriteString writes the s as a "text/plain" content to the client.
func (*Response) WriteTOML ¶
WriteTOML writes an "application/toml" content encoded from the v to the client.
type ReverseProxyModifier ¶ added in v0.12.0
type ReverseProxyModifier struct {
// ModifyRequestMethod modifies the method of the request to the target.
ModifyRequestMethod func(method string) string
// ModifyRequestPath modifies the path of the request to the target.
//
// Note that the path contains the query part (anyway, the HTTP/2
// specification says so). Therefore, the returned path must also be in
// this format.
ModifyRequestPath func(path string) string
// ModifyRequestHeader modifies the header of the request to the target.
ModifyRequestHeader func(header http.Header)
// ModifyRequestBody modifies the body of the request from the target.
ModifyRequestBody func(body io.Reader) (io.Reader, error)
// ModifyResponseStatus modifies the status of the response from the
// target.
ModifyResponseStatus func(status int) int
// ModifyResponseHeader modifies the header of the response from the
// target.
ModifyResponseHeader func(header http.Header)
// ModifyResponseBody modifies the body of the response from the target.
//
// It is the caller's responsibility to close the returned
// `io.ReadCloser`, which means that the `Response.ProxyPass` will be
/// responsible for closing it.
ModifyResponseBody func(body io.ReadCloser) (io.ReadCloser, error)
}
ReverseProxyModifier is used by the `Response.ProxyPass` to modify the request to the target and the response from the traget.
Note that any field in the `ReverseProxyModifier` can be nil, which means there is no need to modify that value.
type WebSocket ¶
type WebSocket struct {
// TextHandler is the handler that handles the incoming text messages of
// the current WebSocket.
TextHandler func(text string) error
// BinaryHandler is the handler that handles the incoming binary
// messages of the current WebSocket.
BinaryHandler func(b []byte) error
// ConnectionCloseHandler is the handler that handles the incoming
// connection close messages of the current WebSocket.
ConnectionCloseHandler func(status int, reason string) error
// PingHandler is the handler that handles the incoming ping messages of
// the current WebSocket.
PingHandler func(appData string) error
// PongHandler is the handler that handles the incoming pong messages of
// the current WebSocket.
PongHandler func(appData string) error
// ErrorHandler is the handler that handles error occurs in the incoming
// messages of the current WebSocket.
ErrorHandler func(err error)
// Closed indicates whether the current WebSocket has been closed.
Closed bool
// contains filtered or unexported fields
}
WebSocket is a WebSocket peer.
It is highly recommended not to modify the handlers of the `WebSocket` after calling the `WebSocket.Listen`, which will cause unpredictable problems.
func (*WebSocket) Listen ¶
func (ws *WebSocket) Listen()
Listen listens for the messages sent from the remote peer of the ws. After one call to it, subsequent calls have no effect.
func (*WebSocket) SetMaxMessageBytes ¶ added in v0.11.0
SetMaxMessageBytes sets the maximum number of bytes the ws will read messages from the remote peer. If a message exceeds the limit, the ws sends a close message to the remote peer and returns an error immediately.
func (*WebSocket) SetReadDeadline ¶ added in v0.11.0
SetReadDeadline sets the read deadline on the underlying connection of the ws. After a read has timed out, the state of the ws is corrupt and all future reads will return an error immediately.
func (*WebSocket) SetWriteDeadline ¶ added in v0.11.0
SetWriteDeadline sets the write deadline on the underlying connection of the ws. After a write has timed out, the state of the ws is corrupt and all future writes will return an error immediately.
func (*WebSocket) WriteBinary ¶
WriteBinary writes the b as a binary message to the remote peer of the ws.
func (*WebSocket) WriteConnectionClose ¶
WriteConnectionClose writes a connection close message to the remote peer of the ws with the status and the reason.
func (*WebSocket) WritePing ¶
WritePing writes a ping message to the remote peer of the ws with the appData.