air

package module
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: May 22, 2019 License: Unlicense Imports: 54 Imported by: 17

README

Air

Build Status Coverage Status Go Report Card GoDoc

An ideally refined web framework for Go.

High-performance? Fastest? Almost all web frameworks are using these words to tell people that they are the best. Maybe they are, maybe not. Air does not intend to follow the crowd. Our goal is always to strive to make it easy for people to use Air to build their web applications. So, we can only guarantee you one thing: Air can serve properly.

FAQ

Q: Why named Air?

A: "A" for "An", "I" for "Ideally" and "R" for "Refined". So, Air.

Q: Why based on the net/http?

A: In fact, I've tried to implement a full-featured HTTP server (just like the awesome valyala/fasthttp). But when I finished about half of the work, I suddenly realized: What about stability? What about those awesome middleware outside? And, seriously, what am I doing?

Q: Why not just use the net/http?

A: Yeah, we can of course use the net/http directly, after all, it can meet many requirements. But, ummm... it's really too stable, isn't it? I mean, to ensure Go's backward compatibility (which is extremely necessary), we can't easily add some handy features to the net/http. And, the http.Request does not only represents the request received by the server, but also represents the request made by the client. In some cases it can be confusing. So why not just use the net/http as the underlying server, and then implement a refined web framework that are only used for the server-side on top of it?

Q: Do you know we already got the gin-gonic/gin and the labstack/echo?

A: Of course, I knew it when I started Go. And, I love both of them! But, why not try some new flavors? Are you sure you prefer them instead of Air? Don't even give Air a try? Wow... well, maybe Air is not for you. After all, it's for people who love to try new things. Relax and continue to maintain the status quo, you will be fine.

Q: What about the fantastic Gorilla web toolkit?

A: Just call the air.WrapHTTPHandler and the air.WrapHTTPMiddleware.

Q: Is Air good enough?

A: Far from enough. But it's already working.

Features

  • API
    • As less as possible
    • As clean as possible
    • As simple as possible
    • As expressive as possible
  • Server
    • HTTP/2 (including h2c) support
    • SSL/TLS support
    • ACME support
    • PROXY protocol support
    • Graceful shutdown support
  • Router
    • Based on the Radix Tree
    • Zero dynamic memory allocation
    • Blazing fast
    • Has a good inspection mechanism
    • Group routes support
  • Gas (aka middleware)
    • Router level:
      • Before router
      • After router
    • Route level
    • Group level
  • WebSocket
    • Full-duplex communication
  • Reverse proxy
    • Retrieves resources on behalf of a client from another server
    • Supported protocols:
      • HTTP(S)
      • WebSocket
      • gRPC (including gRPC-Web)
  • Binder
    • Binds HTTP request body into the provided struct
    • Supported MIME types:
      • application/json
      • application/xml
      • application/protobuf
      • application/msgpack
      • application/toml
      • application/yaml
      • application/x-www-form-urlencoded
      • multipart/form-data
  • Minifier
    • Minifies HTTP response on the fly
    • Supported MIME types:
      • text/html
      • text/css
      • application/javascript
      • application/json
      • application/xml
      • image/svg+xml
  • Gzip
    • Compresses HTTP response by using the gzip
    • Default MIME types:
      • text/plain
      • text/html
      • text/css
      • application/javascript
      • application/json
      • application/xml
      • application/toml
      • application/yaml
      • image/svg+xml
  • Renderer
    • Rich template functions
    • Hot update support
  • Coffer
    • Accesses binary asset files by using the runtime memory
    • Significantly improves the performance of the air.Response.WriteFile
    • Asset file minimization and gzip support
    • Default asset file extensions:
      • .html
      • .css
      • .js
      • .json
      • .xml
      • .toml
      • .yaml
      • .yml
      • .svg
      • .jpg
      • .jpeg
      • .png
      • .gif
    • Hot update support
  • I18n
    • Adapt to the request's favorite conventions
    • Implanted into the air.Response.Render
    • Hot update support
  • Error
    • Centralized handling

Installation

Open your terminal and execute

$ go get github.com/aofei/air

done.

The only requirement is the Go, at least v1.11.

Hello, 世界

Create a file named hello.go

package main

import "github.com/aofei/air"

func main() {
	air.Default.GET("/", func(req *air.Request, res *air.Response) error {
		return res.WriteString("Hello, 世界")
	})
	air.Default.Serve()
}

and run it

$ go run hello.go

then visit http://localhost:8080.

Documentation

Does all web frameworks need to have a complicated (or a lovely but lengthy) website to guide people how to use them? Well, Air has only one GoDoc with useful comments. In fact, Air is so succinct that you don't need to understand how to use it through a large document.

Gases

As we all know that the air of earth is a mixture of gases. So the same is that Air adopts the gas as its composition. Everyone can create new gas and use it within Air simply.

A gas is a function chained in the HTTP request-response cycle with access to the air.Request and the air.Response which it uses to perform a specific action, for example, logging every request or recovering from panics.

return func(next air.Handler) air.Handler {
	return func(req *air.Request, res *air.Response) error {
		// Do something here...
		return next(req, res) // Execute the next handler
	}
}

If you already have some good HTTP middleware, you can simply wrap them into gases by calling the air.WrapHTTPMiddleware.

If you are looking for some useful gases, simply visit here.

Examples

If you want to be familiar with Air as soon as possible, simply visit here.

Community

If you want to discuss Air, or ask questions about it, simply post questions or ideas here.

Contributing

If you want to help build Air, simply follow this to send pull requests here.

License

This project is licensed under the Unlicense.

License can be found here.

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

Constants

This section is empty.

Variables

View Source
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

func DefaultErrorHandler(err error, req *Request, res *Response)

DefaultErrorHandler is the default centralized error handler for the server.

func DefaultMethodNotAllowedHandler

func DefaultMethodNotAllowedHandler(req *Request, res *Response) error

DefaultMethodNotAllowedHandler is the default `Handler` that returns method not allowed error.

func DefaultNotFoundHandler

func DefaultNotFoundHandler(req *Request, res *Response) error

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.
	//
	// 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.
	//
	// 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) BATCH

func (a *Air) BATCH(methods []string, path string, h Handler, gases ...Gas)

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

func (a *Air) CONNECT(path string, h Handler, gases ...Gas)

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) Close

func (a *Air) Close() error

Close closes the server of the a immediately.

func (*Air) DELETE

func (a *Air) DELETE(path string, h Handler, gases ...Gas)

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

func (a *Air) FILE(path, filename string, gases ...Gas)

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

func (a *Air) FILES(prefix, root string, gases ...Gas)

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

func (a *Air) GET(path string, h Handler, gases ...Gas)

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

func (a *Air) Group(prefix string, gases ...Gas) *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

func (a *Air) HEAD(path string, h Handler, gases ...Gas)

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

func (a *Air) OPTIONS(path string, h Handler, gases ...Gas)

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

func (a *Air) PATCH(path string, h Handler, gases ...Gas)

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

func (a *Air) POST(path string, h Handler, gases ...Gas)

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

func (a *Air) PUT(path string, h Handler, gases ...Gas)

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) Serve

func (a *Air) Serve() error

Serve starts the server of the a.

func (*Air) Shutdown

func (a *Air) Shutdown(ctx context.Context) error

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.

func (*Air) TRACE

func (a *Air) TRACE(path string, h Handler, gases ...Gas)

TRACE registers a new TRACE 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.

type Gas

type Gas func(Handler) Handler

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`.

func WrapHTTPMiddleware

func WrapHTTPMiddleware(hm func(http.Handler) http.Handler) Gas

WrapHTTPMiddleware provides a convenient way to wrap an `http.Handler` middleware into a `Gas`.

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.

func (*Group) BATCH

func (g *Group) BATCH(methods []string, path string, h Handler, gases ...Gas)

BATCH is just like the `Air.BATCH`.

func (*Group) CONNECT

func (g *Group) CONNECT(path string, h Handler, gases ...Gas)

CONNECT is just like the `Air.CONNECT`.

func (*Group) DELETE

func (g *Group) DELETE(path string, h Handler, gases ...Gas)

DELETE is just like the `Air.DELETE`.

func (*Group) FILE

func (g *Group) FILE(path, file string, gases ...Gas)

FILE is just like the `Air.FILE`.

func (*Group) FILES added in v0.5.0

func (g *Group) FILES(prefix, root string, gases ...Gas)

FILES is just like the `Air.FILES`.

func (*Group) GET

func (g *Group) GET(path string, h Handler, gases ...Gas)

GET is just like the `Air.GET`.

func (*Group) Group

func (g *Group) Group(prefix string, gases ...Gas) *Group

Group is just like the `Air.Group`.

func (*Group) HEAD

func (g *Group) HEAD(path string, h Handler, gases ...Gas)

HEAD is just like the `Air.HEAD`.

func (*Group) OPTIONS

func (g *Group) OPTIONS(path string, h Handler, gases ...Gas)

OPTIONS is just like the `Air.OPTIONS`.

func (*Group) PATCH

func (g *Group) PATCH(path string, h Handler, gases ...Gas)

PATCH is just like the `Air.PATCH`.

func (*Group) POST

func (g *Group) POST(path string, h Handler, gases ...Gas)

POST is just like the `Air.POST`.

func (*Group) PUT

func (g *Group) PUT(path string, h Handler, gases ...Gas)

PUT is just like the `Air.PUT`.

func (*Group) TRACE

func (g *Group) TRACE(path string, h Handler, gases ...Gas)

TRACE is just like the `Air.TRACE`.

type Handler

type Handler func(*Request, *Response) error

Handler defines a function to serve requests.

func WrapHTTPHandler added in v0.8.4

func WrapHTTPHandler(hh http.Handler) Handler

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

func (r *Request) Bind(v interface{}) error

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

func (r *Request) ClientAddress() string

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

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

Cookie returns the matched `http.Cookie` for the name. It returns nil if not found.

func (*Request) Cookies

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

Cookies returns all `http.Cookie` in the r.

func (*Request) HTTPRequest

func (r *Request) HTTPRequest() *http.Request

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

func (r *Request) LocalizedString(key string) string

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

func (r *Request) RemoteAddress() string

RemoteAddress returns the last network address that sent the r.

func (*Request) SetHTTPRequest

func (r *Request) SetHTTPRequest(hr *http.Request)

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.

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) error

ProxyPass passes the request to the target and writes the response from the target to the client by using the reverse proxy technique.

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

func (r *Response) Redirect(url string) error

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

func (r *Response) Render(m map[string]interface{}, templates ...string) error

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

func (r *Response) SetCookie(c *http.Cookie)

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

func (r *Response) WebSocket() (*WebSocket, error)

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

func (r *Response) WriteFile(filename string) error

WriteFile writes a file content targeted by the filename to the client.

func (*Response) WriteHTML

func (r *Response) WriteHTML(h string) error

WriteHTML writes the h as a "text/html" content to the client.

func (*Response) WriteJSON

func (r *Response) WriteJSON(v interface{}) error

WriteJSON writes an "application/json" content encoded from the v to the client.

func (*Response) WriteMsgpack

func (r *Response) WriteMsgpack(v interface{}) error

WriteMsgpack writes an "application/msgpack" content encoded from the v to the client.

func (*Response) WriteProtobuf

func (r *Response) WriteProtobuf(v interface{}) error

WriteProtobuf writes an "application/protobuf" content encoded from the v to the client.

func (*Response) WriteString

func (r *Response) WriteString(s string) error

WriteString writes the s as a "text/plain" content to the client.

func (*Response) WriteTOML

func (r *Response) WriteTOML(v interface{}) error

WriteTOML writes an "application/toml" content encoded from the v to the client.

func (*Response) WriteXML

func (r *Response) WriteXML(v interface{}) error

WriteXML writes an "application/xml" content encoded from the v to the client.

func (*Response) WriteYAML added in v0.7.1

func (r *Response) WriteYAML(v interface{}) error

WriteYAML writes an "application/yaml" content encoded from the v to the client.

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) Close

func (ws *WebSocket) Close() error

Close closes the ws without sending or waiting for a close message.

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

func (ws *WebSocket) SetMaxMessageBytes(mmb int64)

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

func (ws *WebSocket) SetReadDeadline(t time.Time) error

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

func (ws *WebSocket) SetWriteDeadline(t time.Time) error

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

func (ws *WebSocket) WriteBinary(b []byte) error

WriteBinary writes the b as a binary message to the remote peer of the ws.

func (*WebSocket) WriteConnectionClose

func (ws *WebSocket) WriteConnectionClose(status int, reason string) error

WriteConnectionClose writes a connection close message to the remote peer of the ws with the status and the reason.

func (*WebSocket) WritePing

func (ws *WebSocket) WritePing(appData string) error

WritePing writes a ping message to the remote peer of the ws with the appData.

func (*WebSocket) WritePong

func (ws *WebSocket) WritePong(appData string) error

WritePong writes a pong message to the remote peer of the ws with the appData.

func (*WebSocket) WriteText

func (ws *WebSocket) WriteText(text string) error

WriteText writes the text as a text message to the remote peer of the ws.

Jump to

Keyboard shortcuts

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