Documentation
¶
Index ¶
- Constants
- Variables
- func DefaultHTTPErrorHandler(err error, c *Context)
- type Air
- func (a *Air) Close() error
- func (a *Air) Contain(gases ...Gas)
- func (a *Air) DELETE(path string, h Handler, gases ...Gas)
- func (a *Air) File(path, file string)
- func (a *Air) GET(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) Precontain(gases ...Gas)
- func (a *Air) Serve() error
- func (a *Air) Shutdown(c *Context) error
- func (a *Air) Static(prefix, root string)
- func (a *Air) URL(h Handler, params ...interface{}) string
- type Asset
- type Binder
- type Coffer
- type Config
- type Context
- func (c *Context) Attachment(file, filename string) error
- func (c *Context) Bind(i interface{}) error
- func (c *Context) Blob(contentType string, b []byte) error
- func (c *Context) Cookie(name string) (*http.Cookie, error)
- func (c *Context) Cookies() []*http.Cookie
- func (c *Context) File(file string) error
- func (c *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
- func (c *Context) FormValue(key string) string
- func (c *Context) FormValues() url.Values
- func (c *Context) HTML(html string) error
- func (c *Context) HasFormValue(key string) bool
- func (c *Context) HasQueryValue(key string) bool
- func (c *Context) Inline(file, filename string) error
- func (c *Context) JSON(i interface{}) error
- func (c *Context) JSONP(i interface{}, callback string) error
- func (c *Context) NoContent() error
- func (c *Context) Param(name string) string
- func (c *Context) Push(target string, pos *http.PushOptions) error
- func (c *Context) QueryValue(key string) string
- func (c *Context) QueryValues() url.Values
- func (c *Context) Redirect(statusCode int, url string) error
- func (c *Context) Render(templates ...string) error
- func (c *Context) SetCancel()
- func (c *Context) SetCookie(cookie *http.Cookie)
- func (c *Context) SetDeadline(deadline time.Time)
- func (c *Context) SetTimeout(timeout time.Duration)
- func (c *Context) SetValue(key interface{}, val interface{})
- func (c *Context) Stream(contentType string, r io.Reader) error
- func (c *Context) String(s string) error
- func (c *Context) XML(i interface{}) error
- type Gas
- type Group
- func (g *Group) Contain(gases ...Gas)
- func (g *Group) DELETE(path string, h Handler, gases ...Gas)
- func (g *Group) File(path, file string)
- func (g *Group) GET(path string, h Handler, gases ...Gas)
- func (g *Group) NewSubGroup(prefix string, gases ...Gas) *Group
- func (g *Group) POST(path string, h Handler, gases ...Gas)
- func (g *Group) PUT(path string, h Handler, gases ...Gas)
- func (g *Group) Static(prefix, root string)
- type HTTPError
- type HTTPErrorHandler
- type Handler
- type Logger
- type Map
- type Minifier
- type Renderer
- type Request
- type Response
- func (r *Response) Attachment(file, filename string) error
- func (r *Response) Blob(contentType string, b []byte) error
- func (r *Response) File(file string) error
- func (r *Response) HTML(html string) error
- func (r *Response) Inline(file, filename string) error
- func (r *Response) JSON(i interface{}) error
- func (r *Response) JSONP(i interface{}, callback string) error
- func (r *Response) NoContent() error
- func (r *Response) Redirect(statusCode int, url string) error
- func (r *Response) Render(templates ...string) error
- func (r *Response) SetCookie(cookie *http.Cookie)
- func (r *Response) Stream(contentType string, reader io.Reader) error
- func (r *Response) String(s string) error
- func (r *Response) Write(b []byte) (int, error)
- func (r *Response) WriteHeader(statusCode int)
- func (r *Response) XML(i interface{}) error
- type URL
Constants ¶
const ( MIMEApplicationJSON = "application/json" MIMEApplicationJavaScript = "application/javascript" MIMEApplicationXML = "application/xml" MIMEApplicationXWWWFormURLEncoded = "application/x-www-form-urlencoded" MIMEImageJPEG = "image/jpeg" MIMEImagePNG = "image/png" MIMEImageSVGXML = "image/svg+xml" MIMEMultipartFormData = "multipart/form-data" MIMETextCSS = "text/css" MIMETextHTML = "text/html" MIMETextJavaScript = "text/javascript" MIMETextPlain = "text/plain" MIMETextXML = "text/xml" CharsetUTF8 = "; charset=utf-8" )
MIME types
const ( GET = "GET" POST = "POST" PUT = "PUT" DELETE = "DELETE" )
HTTP methods
const ( HeaderAccept = "Accept" HeaderAcceptCharset = "Accept-Charset" HeaderAcceptEncoding = "Accept-Encoding" HeaderAcceptLanguage = "Accept-Language" HeaderAcceptRanges = "Accept-Ranges" HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" HeaderAccessControlMaxAge = "Access-Control-Max-Age" HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" HeaderAccessControlRequestMethod = "Access-Control-Request-Method" HeaderAge = "Age" HeaderAllow = "Allow" HeaderAuthorization = "Authorization" HeaderCacheControl = "Cache-Control" HeaderConnection = "Connection" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLanguage = "Content-Language" HeaderContentLength = "Content-Length" HeaderContentLocation = "Content-Location" HeaderContentSecurityPolicy = "Content-Security-Policy" HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only" HeaderContentType = "Content-Type" HeaderCookie = "Cookie" HeaderDNT = "DNT" HeaderDate = "Date" HeaderETag = "ETag" HeaderExpires = "Expires" HeaderForm = "Form" HeaderHost = "Host" HeaderIfMatch = "If-Match" HeaderIfModifiedSince = "If-Modified-Since" HeaderIfNoneMatch = "If-None-Match" HeaderIfRange = "If-Range" HeaderIfUnmodifiedSince = "If-Unmodified-Since" HeaderKeepAlive = "Keep-Alive" HeaderLastModified = "Last-Modified" HeaderLocation = "Location" HeaderOrigin = "Origin" HeaderPublicKeyPins = "Public-Key-Pins" HeaderPublicKeyPinsReportOnly = "Public-Key-Pins-Report-Only" HeaderReferer = "Referer" HeaderReferrerPolicy = "Referrer-Policy" HeaderRetryAfter = "Retry-After" HeaderServer = "Server" HeaderSetCookie = "Set-Cookie" HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderTE = "TE" HeaderTK = "TK" HeaderTrailer = "Trailer" HeaderTransferEncoding = "Transfer-Encoding" HeaderUpgrade = "Upgrade" HeaderUpgradeInsecureRequests = "Upgrade-Insecure-Requests" HeaderUserAgent = "User-Agent" HeaderVary = "Vary" HeaderVia = "Via" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderWarning = "Warning" HeaderXCSRFToken = "X-CSRF-Token" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXDNSPrefetchControl = "X-DNS-Prefetch-Control" HeaderXForwardedFor = "X-Forwarded-For" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXFrameOptions = "X-Frame-Options" HeaderXHTTPMethodOverride = "X-HTTP-Method-Override" HeaderXRealIP = "X-Real-IP" HeaderXXSSProtection = "X-XSS-Protection" )
HTTP headers
Variables ¶
var ( ErrNotFound = NewHTTPError(http.StatusNotFound) // 404 ErrMethodNotAllowed = NewHTTPError(http.StatusMethodNotAllowed) // 405 ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge) // 413 ErrUnsupportedMediaType = NewHTTPError(http.StatusUnsupportedMediaType) // 415 ErrInternalServerError = NewHTTPError(http.StatusInternalServerError) // 500 ErrBadGateway = NewHTTPError(http.StatusBadGateway) // 502 ErrGatewayTimeout = NewHTTPError(http.StatusGatewayTimeout) // 504 ErrInvalidRedirectCode = errors.New("invalid redirect status code") )
HTTP errors
var ( NotFoundHandler = func(c *Context) error { return ErrNotFound } MethodNotAllowedHandler = func(c *Context) error { return ErrMethodNotAllowed } )
HTTP error handlers
var DefaultConfig = Config{ AppName: "air", LogFormat: `{"app_name":"{{.app_name}}","time":"{{.time_rfc3339}}","level":"{{.level}}",` + `"file":"{{.short_file}}","line":"{{.line}}"}`, Address: "localhost:2333", MaxHeaderBytes: 1 << 20, TemplateRoot: "templates", TemplateExts: []string{".html"}, TemplateLeftDelim: "{{", TemplateRightDelim: "}}", AssetRoot: "assets", AssetExts: []string{".html", ".css", ".js", ".json", ".xml", ".svg"}, }
DefaultConfig is the default instance of the `Config`.
Functions ¶
func DefaultHTTPErrorHandler ¶
DefaultHTTPErrorHandler is the default HTTP error handler.
Types ¶
type Air ¶
type Air struct { Config *Config Logger Logger Binder Binder Minifier Minifier Renderer Renderer Coffer Coffer HTTPErrorHandler HTTPErrorHandler // contains filtered or unexported fields }
Air is the top-level framework struct.
func (*Air) DELETE ¶
DELETE registers a new DELETE route for the path with the matching h in the router with the optional route-level gases.
func (*Air) GET ¶
GET registers a new GET route for the path with the matching h in the router with the optional route-level gases.
func (*Air) POST ¶
POST registers a new POST route for the path with the matching h in the router with the optional route-level gases.
func (*Air) PUT ¶
PUT registers a new PUT route for the path with the matching h in the router with the optional route-level gases.
func (*Air) Precontain ¶
Precontain adds the gases to the chain which is perform before the router.
func (*Air) Shutdown ¶
Shutdown gracefully shuts down the HTTP server without interrupting any active connections.
type Asset ¶
type Asset struct {
// contains filtered or unexported fields
}
Asset is a binary asset file.
type Binder ¶
type Binder interface { // Bind binds the body of the req into the provided type i. Bind(i interface{}, req *Request) error }
Binder is used to provide a `Bind()` method for an `Air` instance for binds an HTTP request body into privided type.
type Coffer ¶
type Coffer interface { // Init initializes the `Coffer`. It will be called in the `Air#Serve()`. Init() error // Asset returns an `Asset` in the `Coffer` for the provided name. // // **Please use the `filepath.Abs()` to process the name before calling.** Asset(name string) *Asset }
Coffer is used to provide an `Asset()` method for an `Air` instance for accesses binary asset files by using the runtime memory.
type Config ¶
type Config struct { // AppName represents the name of the `Air` instance. // // The default Value is "air". // // It's called "app_name" in the config file. AppName string // DebugMode indicates whether to enable the debug mode when the HTTP server is started. // // The default value is false. // // It's called "debug_mode" in the config file. DebugMode bool // LoggerEnabled indicates whether to enable the `Logger` when the HTTP server is started. // It works only with the default `Logger`. // // It will be forced to the true if the `DebugMode` is true. // // The default value is false. // // It's called "logger_enabled" in the config file. LoggerEnabled bool // LogFormat represents the format of the output content of the `Logger`. It works only with // the default `Logger` and when the `LoggerEnabled` is true. // // The default value is: // `{"app_name":"{{.app_name}}","time":"{{.time_rfc3339}}","level":"{{.level}}",` + // `"file":"{{.short_file}}","line":"{{.line}}"}` // // It's called "log_format" in the config file. LogFormat string // Address represents the TCP address that the HTTP server to listen on. // // The default value is "localhost:2333". // // It's called "address" in the config file. Address string // ReadTimeout represents the maximum duration before timing out read of the HTTP request. // // The default value is 0. // // It's called "read_timeout" in the config file. // // **It's unit in the config file is MILLISECONDS.** ReadTimeout time.Duration // WriteTimeout represents the maximum duration before timing out write of the HTTP // response. // // The default value is 0. // // It's called "write_timeout" in the config file. // // **It's unit in the config file is MILLISECONDS.** WriteTimeout time.Duration // MaxHeaderBytes represents the maximum number of bytes the HTTP server will read parsing // the HTTP request header's keys and values, including the HTTP request line. It does not // limit the size of the HTTP request body. // // The default value is 1048576. // // It's called "max_header_bytes" in the config file. MaxHeaderBytes int // TLSCertFile represents the path of the TLS certificate file. // // The default value is "". // // It's called "tls_cert_file" in the config file. TLSCertFile string // TLSKeyFile represents the path of the TLS key file. // // The default value is "". // // It's called "tls_key_file" in the config file. TLSKeyFile string // TemplateRoot represents the root directory of the HTML templates. It will be parsed into // the `Renderer`. It works only with the default `Renderer`. // // The default value is "templates" that means a subdirectory of the runtime directory. // // It's called "template_root" in the config file. TemplateRoot string // TemplateExts represents the file name extensions of the HTML templates. It will be used // when parsing the HTML templates. It works only with the default `Renderer`. // // The default value is [".html"]. // // It's called "template_exts" in the config file. TemplateExts []string // TemplateLeftDelim represents the left side of the HTML template delimiter. It will be // used when parsing the HTML templates. It works only with the default `Renderer`. // // The default value is "{{". // // It's called "template_left_delim" in the config file. TemplateLeftDelim string // TemplateRightDelim represents the right side of the HTML template delimiter. It will be // used when parsing the HTML templates. It works only with the default `Renderer`. // // The default value is "}}". // // It's called "template_right_delim" in the config file. TemplateRightDelim string // TemplateMinified indicates whether to minify the HTML templates before they being parsed // into the `Renderer`. It works only with the default `Renderer`. // // The default value is false. // // It's called "template_minified" in the config file. TemplateMinified bool // CofferEnabled indicates whether to enable the `Coffer` when the HTTP server is started. // It works only with the default `Coffer`. // // The default value is false. // // It's called "coffer_enabled" in the config file. CofferEnabled bool // AssetRoot represents the root directory of the asset files. It will be loaded into the // `Coffer`. It works only with the default `Coffer` and when the `CofferEnabled` is true. // // The default value is "assets" that means a subdirectory of the runtime directory. // // It's called "asset_root" in the config file. AssetRoot string // AssetExts represents the file name extensions of the asset files. It will be used when // loading the asset files. It works only with the default `Coffer` and when the // `CofferEnabled` is true. // // The default value is [".html", ".css", ".js", ".json", ".xml", ".svg"]. // // It's called "asset_exts" in the config file. AssetExts []string // AssetMinified indicates whether to minify the asset files before they being loaded into // the `Coffer`. It works only with the default `Coffer` and when the `CofferEnabled` is // true. // // The default value is false. // // It's called "asset_minified" in the config file. AssetMinified bool // Data represents the data that parsing from the config file. You can use it to access the // values in the config file. // // e.g. Data["foobar"] will accesses the value in the config file called "foobar". Data Map }
Config is a global set of configs that for an instance of the `Air` for customization.
type Context ¶
type Context struct { context.Context Air *Air Request *Request Response *Response PristinePath string ParamNames []string ParamValues []string Handler Handler // Cancel is non-nil if one of the `SetCancel()`, the `SetDeadline()` or the `SetTimeout()` // is called. It will be called when the HTTP server finishes the current cycle if it is // non-nil and has never been called. Cancel context.CancelFunc // Data is an alias for the `Response#Data`. Data Map }
Context represents the context of the current HTTP request.
It's embedded with the `context.Context`.
func NewContext ¶
NewContext returns a pointer of a new instance of the `Context`.
func (*Context) Attachment ¶
Attachment is an alias for the `Response#Attachment()` of the c.
func (*Context) FormValues ¶
FormValues is an alias for the `Request#FormValues()` of the c.
func (*Context) HasFormValue ¶
HasFormValue is an alias for the `Request#HasFormValue()` of the c.
func (*Context) HasQueryValue ¶
HasQueryValue is an alias for the `Request#HasQueryValue()` of the c.
func (*Context) Push ¶
func (c *Context) Push(target string, pos *http.PushOptions) error
Push is an alias for the `Response#Push()` of the c.
func (*Context) QueryValue ¶
QueryValue is an alias for the `Request#QueryValue()` of the c.
func (*Context) QueryValues ¶
QueryValues is an alias for the `Request#QueryValues()` of the c.
func (*Context) SetCancel ¶
func (c *Context) SetCancel()
SetCancel sets a new done channel into the `Context` of the c.
func (*Context) SetDeadline ¶
SetDeadline sets a new deadline into the `Context` of the c.
func (*Context) SetTimeout ¶
SetTimeout sets a new deadline based on the timeout into the `Context` of the c.
func (*Context) SetValue ¶
func (c *Context) SetValue(key interface{}, val interface{})
SetValue sets request-scoped value into the `Context` of the c.
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group is a set of sub-routes for a specified route. It can be used for inner routes that share a common gas or functionality that should be separate from the parent `Air` instance while still inheriting from it.
func NewGroup ¶
NewGroup returns a pointer of a new router group with the prefix and the optional group-level gases.
func (*Group) NewSubGroup ¶
NewSubGroup creates a pointer of a new sub-group with the prefix and the optional sub-group-level gases.
type HTTPError ¶
HTTPError represents an error that occurred while handling an HTTP request.
func NewHTTPError ¶
NewHTTPError returns a pointer of a new instance of the `HTTPError`.
type HTTPErrorHandler ¶
HTTPErrorHandler is a centralized HTTP error handler.
type Handler ¶
Handler defines a function to serve HTTP requests.
func WrapHandler ¶
WrapHandler wraps the h into the `Handler`.
type Logger ¶
type Logger interface { // Output returns the output of the `Logger`. Output() io.Writer // SetOutput sets the w to the output of the `Logger`. SetOutput(w io.Writer) // Print prints the log info with the provided type i. Print(i ...interface{}) // Printf prints the log info in the format with the provided args. Printf(format string, args ...interface{}) // Printj prints the log info in the JSON format with the provided m. Printj(m Map) // Debug prints the DEBUG level log info with the provided type i. Debug(i ...interface{}) // Debugf prints the DEBUG level log info in the format with the provided args. Debugf(format string, args ...interface{}) // Debugj prints the DEBUG level log info in the JSON format with the provided m. Debugj(m Map) // Info prints the INFO level log info with the provided type i. Info(i ...interface{}) // Infof prints the INFO level log info in the format with the provided args. Infof(format string, args ...interface{}) // Infoj prints the INFO level log info in the JSON format with the provided m. Infoj(m Map) // Warn prints the WARN level log info with the provided type i. Warn(i ...interface{}) // Warnf prints the WARN level log info in the format with the provided args. Warnf(format string, args ...interface{}) // Warnj prints the WARN level log info in the JSON format with the provided m. Warnj(m Map) // Error prints the ERROR level log info with the provided type i. Error(i ...interface{}) // Errorf prints the ERROR level log info in the format with the provided args. Errorf(format string, args ...interface{}) // Errorj prints the ERROR level log info in the JSON format with the provided m. Errorj(m Map) // Fatal prints the FATAL level log info with the provided type i. Fatal(i ...interface{}) // Fatalf prints the FATAL level log info in the format with the provided args. Fatalf(format string, args ...interface{}) // Fatalj prints the FATAL level log info in the JSON format with the provided m. Fatalj(m Map) }
Logger is used to log information generated in the runtime.
type Minifier ¶
type Minifier interface { // Init initializes the `Minifier`. It will be called in the `Air#Serve()`. Init() error // Minify minifies the b by the mimeType. Minify(mimeType string, b []byte) ([]byte, error) }
Minifier is used to provide a `Minify()` method for an `Air` instance for minifies a content by a MIME type.
type Renderer ¶
type Renderer interface { // Init initializes the `Renderer`. It will be called in the `Air#Serve()`. Init() error // SetTemplateFunc sets the func f into the `Renderer` with the name. SetTemplateFunc(name string, f interface{}) // Render renders the data into the w with the templateName. Render(w io.Writer, templateName string, data Map) error }
Renderer is used to provide a `Render()` method for an `Air` instance for renders a "text/html" HTTP response.
type Request ¶
Request represents the current HTTP request.
It's embedded with the `http.Request`.
func NewRequest ¶
NewRequest returns a pointer of a new instance of the `Request`.
func (*Request) Bind ¶
Bind binds the HTTP body of the r into the provided type i. The default `Binder` does it based on the "Content-Type" header.
func (*Request) FormValues ¶
FormValues returns the form values.
func (*Request) HasFormValue ¶
HasFormValue reports whether the form values contains the form value for the provided key.
func (*Request) HasQueryValue ¶
HasQueryValue is an alias for the `URL#HasQueryValue()` of the r.
func (*Request) QueryValue ¶
QueryValue is an alias for the `URL#QueryValue()` of the r.
func (*Request) QueryValues ¶
QueryValues is an alias for the `URL#QueryValues()` of the r.
type Response ¶
type Response struct { http.ResponseWriter http.Hijacker http.CloseNotifier http.Flusher http.Pusher StatusCode int Size int Written bool Data Map // contains filtered or unexported fields }
Response represents the current HTTP response.
It's embedded with the `http.ResponseWriter`, the `http.Hijacker`, the `http.CloseNotifier`, the `http.Flusher` and the `http.Pusher`.
func NewResponse ¶
NewResponse returns a pointer of a new instance of the `Response`.
func (*Response) Attachment ¶
Attachment sends an HTTP response with the file and the filename as attachment, prompting client to save the file.
func (*Response) Inline ¶
Inline sends an HTTP response with the file and the filename as inline, opening the file in the browser.
func (*Response) JSONP ¶
JSONP sends an "application/javascript" HTTP response with the type i. It uses the callback to construct the JSONP payload.
func (*Response) Redirect ¶
Redirect redirects the current HTTP request to the url with the statusCode.
func (*Response) Render ¶
Render renders one or more HTML templates with the `Data` of the r and sends a "text/html" HTTP response. The default `Renderer` does it by using the `template.Template`. the rults rendered by the former can be inherited by accessing the `Data["InheritedHTML"]` of the r.
func (*Response) SetCookie ¶
SetCookie adds a "Set-Cookie" header in the r. The provided cookie must have a valid `Name`. Invalid cookies may be silently dropped.
func (*Response) Stream ¶
Stream sends a streaming HTTP response with the contentType and the reader.
func (*Response) WriteHeader ¶
WriteHeader implements the `http.ResponseWriter#WriteHeader()`.
type URL ¶
URL represents the HTTP URL of the current HTTP request.
It's embedded with the `url.URL`.
func (*URL) HasQueryValue ¶
HasQueryValue reports whether the query values contains the query value for the provided key.
func (*URL) QueryValue ¶
QueryValue returns the query value in the u for the provided key.
func (*URL) QueryValues ¶
QueryValues returns the query values in the u.