air

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2018 License: Unlicense Imports: 49 Imported by: 17

README

Air

Build Status Coverage Status Go Report Card GoDoc

An ideally refined web framework for Go. You can use it to build a web application as natural as breathing.

High-performance? Fastest? Almost all the 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. It can only guarantee you one thing: it 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.WrapHTTPMiddleware().

Q: Is Air good enough?

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

Features

  • API
    • As less as possible
    • As simple as possible
    • As expressive as possible
  • Method
    • GET (cache-friendly)
    • HEAD (cache-friendly)
    • POST
    • PUT
    • PATCH
    • DELETE
    • CONNECT
    • OPTIONS
    • TRACE
  • Logger
    • DEBUG
    • INFO
    • WARN
    • ERROR
    • FATAL
    • PANIC
  • Server
    • HTTP/2 support
    • SSL/TLS support
    • ACME 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
    • Protocols:
      • HTTP(S)
      • WebSocket
      • gRPC
  • Binder
    • Binds HTTP request body into the provided struct
    • Supported MIME types:
      • application/json
      • application/xml
      • application/msgpack
      • application/x-msgpack
      • application/protobuf
      • application/x-protobuf
      • application/toml
      • application/x-toml
      • 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
      • 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 support
    • 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.9.

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 the 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 is a mixture of gases. So the same is that this framework adopts the gas as its composition. Everyone can create new gas and use it within this framework 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.

If you have got 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 this framework as soon as possible, simply visit here.

Community

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

Contributing

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

License

This project is licensed under the Unlicense.

License can be found here.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Default = New()

Default is the default instance of the `Air`.

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.
	//
	// The default value is "air".
	//
	// It is called "app_name" when it is used as a configuration item.
	AppName string

	// MaintainerEmail is the e-mail address of the one who is responsible
	// for maintaining the current web application.
	//
	// The default value is "".
	//
	// It is called "maintainer_email" when it is used as a configuration
	// item.
	MaintainerEmail string

	// DebugMode indicates whether the current web application is in debug
	// mode.
	//
	// ATTENTION: Some features will be affected in debug mode.
	//
	// The default value is false.
	//
	// It is called "debug_mode" when it is used as a configuration item.
	DebugMode bool

	// LoggerLevel is the level of the logger.
	//
	// It only works when the `DebugMode` is false.
	//
	// The default value is the `LoggerLevelInfo`.
	//
	// It is called "logger_level" when it is used as a configuration item.
	LoggerLevel LoggerLevel

	// LoggerOutput is the output destination of the logger.
	//
	// The default value is the `os.Stdout`.
	LoggerOutput io.Writer

	// Address is the TCP address that the server listens on.
	//
	// The default value is ":8080".
	//
	// It is called "address" when it is used as a configuration item.
	Address string

	// HostWhitelist is the hosts allowed by the server.
	//
	// It only works when the `DebugMode` is false.
	//
	// The default value is nil.
	//
	// It is called "host_whitelist" when it is used as a configuration
	// item.
	HostWhitelist []string

	// ReadTimeout is the maximum duration the server reads the request.
	//
	// The default value is 0.
	//
	// It is called "read_timeout" when it is used as a configuration item.
	ReadTimeout time.Duration

	// ReadHeaderTimeout is the amount of time allowed the server reads the
	// request headers.
	//
	// The default value is 0.
	//
	// It is called "read_header_timeout" when it is used as a configuration
	// item.
	ReadHeaderTimeout time.Duration

	// WriteTimeout is the maximum duration the server writes an response.
	//
	// The default value is 0.
	//
	// It is called "write_timeout" when it is used as a configuration item.
	WriteTimeout time.Duration

	// IdleTimeout is the maximum amount of time the server waits for the
	// next request. If it is zero, the value of `ReadTimeout` is used. If
	// both are zero, the value `ReadHeaderTimeout` is used.
	//
	// The default value is 0.
	//
	// It is called "idle_timeout" when it is used as a configuration item.
	IdleTimeout time.Duration

	// MaxHeaderBytes is the maximum number of bytes the server will read
	// parsing the request header's names and values, including the request
	// line.
	//
	// The default value is 1048576.
	//
	// It is called "max_header_bytes" when it is used as a configuration
	// item.
	MaxHeaderBytes int

	// TLSCertFile is the path to the TLS certificate file used when
	// starting the server.
	//
	// The default value is "".
	//
	// It is called "tls_cert_file" when it is used as a configuration item.
	TLSCertFile string

	// TLSKeyFile is the path to the TLS key file used when starting the
	// server.
	//
	// The default value is "".
	//
	// It is called "tls_key_file" when it is used as a configuration item.
	TLSKeyFile string

	// ACMEEnabled indicates whether the ACME is enabled.
	//
	// It only works when the `DebugMode` is false and both of the
	// `TLSCertFile` and the `TLSKeyFile` are empty.
	//
	// The default value is false.
	//
	// It is called "acme_enabled" when it is used as a configuration item.
	ACMEEnabled bool

	// ACMECertRoot is the root of the ACME certificates.
	//
	// The default value is "acme-certs".
	//
	// It is called "acme_cert_root" when it is used as a configuration
	// item.
	ACMECertRoot string

	// HTTPSEnforced indicates whether the HTTPS is enforced.
	//
	// The default value is false.
	//
	// It is called "https_enforced" when it is used as a configuration
	// item.
	HTTPSEnforced bool

	// WebSocketHandshakeTimeout is the maximum amount of time the server
	// waits for the WebSocket handshake to complete.
	//
	// The default value is 0.
	//
	// It is called "websocket_handshake_timeout" when it is used as a
	// configuration item.
	WebSocketHandshakeTimeout time.Duration

	// WebSocketSubprotocols is the server's supported WebSocket
	// subprotocols.
	//
	// The default value is nil.
	//
	// It is called "websocket_subprotocols" when it is used as a
	// configuration item.
	WebSocketSubprotocols []string

	// NotFoundHandler is a `Handler` that returns not found error.
	//
	// The default value is the `DefaultNotFoundHandler`.
	NotFoundHandler func(*Request, *Response) error

	// MethodNotAllowedHandler is a `Handler` that returns method not
	// allowed error.
	//
	// The default value is the `DefaultMethodNotAllowedHandler`.
	MethodNotAllowedHandler func(*Request, *Response) error

	// ErrorHandler is the centralized error handler for the server.
	//
	// The default value is the `DefaultErrorHandler`.
	ErrorHandler func(error, *Request, *Response)

	// Pregases is the `Gas` chain that performs before routing.
	//
	// The default value is nil.
	Pregases []Gas

	// Gases is the `Gas` chain that performs after routing.
	//
	// The default value is nil.
	Gases []Gas

	// AutoPushEnabled indicates whether the auto push is enabled.
	//
	// The default value is false.
	//
	// It is called "auto_push_enabled" when it is used as a configuration
	// item.
	AutoPushEnabled bool

	// MinifierEnabled indicates whether the minifier is enabled.
	//
	// The default value is false.
	//
	// It is called "minifier_enabled" when it is used as a configuration
	// item.
	MinifierEnabled bool

	// MinifierMIMETypes is the MIME types that will be minified.
	// Unsupported MIME types will be silently ignored.
	//
	// The default value is ["text/html", "text/css",
	// "application/javascript", "application/json", "application/xml",
	// "image/svg+xml"].
	//
	// It is called "minifier_mime_types" when it is used as a configuration
	// item.
	MinifierMIMETypes []string

	// GzipEnabled indicates whether the gzip is enabled.
	//
	// The default value is false.
	//
	// It is called "gzip_enabled" when it is used as a configuration item.
	GzipEnabled bool

	// GzipCompressionLevel is the compression level of the gzip.
	//
	// The default value is `gzip.DefaultCompression`.
	//
	// It is called "gzip_compression_level" when it is used as a
	// configuration item.
	GzipCompressionLevel int

	// GzipMIMETypes is the MIME types that will be gzipped.
	//
	// The default value is ["text/plain", "text/html", "text/css",
	// "application/javascript", "application/json", "application/xml",
	// "image/svg+xml"].
	//
	// It is called "gzip_mime_types" when it is used as a configuration
	// item.
	GzipMIMETypes []string

	// TemplateRoot is the root of the HTML templates. All the HTML
	// templates inside it will be recursively parsed into the renderer.
	//
	// The default value is "templates".
	//
	// It is called "template_root" when it is used as a configuration item.
	TemplateRoot string

	// TemplateExts is the filename extensions of the HTML templates used to
	// distinguish the HTML template files in the `TemplateRoot` when
	// parsing them into the renderer.
	//
	// The default value is [".html"].
	//
	// It is called "template_exts" when it is used as a configuration item.
	TemplateExts []string

	// TemplateLeftDelim is the left side of the HTML template delimiter the
	// renderer renders the HTML templates.
	//
	// The default value is "{{".
	//
	// It is called "template_left_delim" when it is used as a configuration
	// item.
	TemplateLeftDelim string

	// TemplateRightDelim is the right side of the HTML template delimiter
	// the renderer renders the HTML templates.
	//
	// The default value is "}}".
	//
	// It is called "template_right_delim" when it is used as a
	// configuration item.
	TemplateRightDelim string

	// TemplateFuncMap is the HTML template function map the renderer
	// renders the HTML templates.
	//
	// The default value contains strlen, substr and timefmt.
	TemplateFuncMap map[string]interface{}

	// CofferEnabled indicates whether the coffer is enabled.
	//
	// The default value is false.
	//
	// It is called "coffer_enabled" when it is used as a configuration
	// item.
	CofferEnabled bool

	// CofferMaxMemoryBytes is the maximum number of bytes of the runtime
	// memory the coffer will use.
	//
	// The default value is 33554432.
	//
	// It is called "coffer_max_memory_bytes" when it is used as a
	// configuration item.
	CofferMaxMemoryBytes int

	// AssetRoot is the root of the asset files. All the asset files inside
	// it will be recursively parsed into the coffer.
	//
	// The default value is "assets".
	//
	// It is called "asset_root" when it is used as a configuration item.
	AssetRoot string

	// AssetExts is the filename extensions of the asset files used to
	// distinguish the asset files in the `AssetRoot` when loading them into
	// the coffer.
	//
	// The default value is [".html", ".css", ".js", ".json", ".xml",
	// ".svg", ".jpg", ".jpeg", ".png", ".gif"].
	//
	// It is called "asset_exts" when it is used as a configuration item.
	AssetExts []string

	// I18nEnabled indicates whether the i18n is enabled.
	//
	// The default value is false.
	//
	// It is called "i18n_enabled" when it is used as a configuration item.
	I18nEnabled bool

	// LocaleRoot is the root of the locale files. All the locale files
	// inside it will be parsed into the i18n.
	//
	// The default value is "locales".
	//
	// It is called "locale_root" when it is used as a configuration item.
	LocaleRoot string

	// LocaleBase is the base of the locale files. It will be used when a
	// locale file cannot be found.
	//
	// The default value is "en-US".
	//
	// It is called "locale_base" when it is used as a configuration item.
	LocaleBase string

	// ConfigFile is the TOML-based configuration file that will be parsed
	// into the matching configuration items before starting the server.
	//
	// The default value is "".
	ConfigFile string
	// contains filtered or unexported fields
}

Air is the top-level struct of this framework.

func New

func New() *Air

New returns a new instance of the `Air`.

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

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 with the optional route-level gases.

func (*Air) Close

func (a *Air) Close() error

Close closes the server immediately.

func (*Air) DEBUG

func (a *Air) DEBUG(msg string, extras ...map[string]interface{})

DEBUG logs the msg at the `LoggerLevelDebug` with the optional extras.

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 with the optional route-level gases.

func (*Air) ERROR

func (a *Air) ERROR(msg string, extras ...map[string]interface{})

ERROR logs the msg at the `LoggerLevelError` with the optional extras.

func (*Air) FATAL

func (a *Air) FATAL(msg string, extras ...map[string]interface{})

FATAL logs the msg at the `LoggerLevelFatal` with the optional extras followed by a call to `os.Exit(1)`.

func (*Air) FILE

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

FILE registers a new route with the path to serve a static file with the filename and the optional route-level gases.

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 with the optional route-level gases.

func (*Air) Group

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

Group returns a new instance of the `Group` with the prefix and the optional group-level gases.

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 with the optional route-level gases.

func (*Air) INFO

func (a *Air) INFO(msg string, extras ...map[string]interface{})

INFO logs the msg at the `LoggerLevelInfo` with the optional extras.

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 with the optional route-level gases.

func (*Air) PANIC

func (a *Air) PANIC(msg string, extras ...map[string]interface{})

PANIC logs the msg at the `LoggerLevelPanic` with the optional extras followed by a call to `panic()`.

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 with the optional route-level gases.

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 with the optional route-level gases.

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 with the optional route-level gases.

func (*Air) STATIC

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

STATIC registers a new route with the path prefix to serve the static files from the root with the optional route-level gases.

func (*Air) Serve

func (a *Air) Serve() error

Serve starts the server.

func (*Air) Shutdown

func (a *Air) Shutdown(timeout time.Duration) error

Shutdown gracefully shuts down the server without interrupting any active connections until timeout. It waits indefinitely for connections to return to idle and then shut down when the timeout is less than or equal to zero.

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 with the optional route-level gases.

func (*Air) WARN

func (a *Air) WARN(msg string, extras ...map[string]interface{})

WARN logs the msg at the `LoggerLevelWarn` with the optional extras.

type Gas

type Gas func(Handler) Handler

Gas defines a function to process gases.

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 the route paths of the current group.
	Prefix string

	// Gases is the group-level gases of the current group.
	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 implements the `Air#BATCH()`.

func (*Group) CONNECT

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

CONNECT implements the `Air#CONNECT()`.

func (*Group) DELETE

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

DELETE implements the `Air#DELETE()`.

func (*Group) FILE

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

FILE implements the `Air#FILE()`.

func (*Group) GET

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

GET implements the `Air#GET()`.

func (*Group) Group

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

Group implements the `Air#Group()`.

func (*Group) HEAD

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

HEAD implements the `Air#HEAD()`.

func (*Group) OPTIONS

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

OPTIONS implements the `Air#OPTIONS()`.

func (*Group) PATCH

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

PATCH implements the `Air#PATCH()`.

func (*Group) POST

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

POST implements the `Air#POST()`.

func (*Group) PUT

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

PUT implements the `Air#PUT()`.

func (*Group) STATIC

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

STATIC implements the `Air#STATIC()`.

func (*Group) TRACE

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

TRACE implements the `Air#TRACE()`.

type Handler

type Handler func(*Request, *Response) error

Handler defines a function to serve requests.

type LoggerLevel

type LoggerLevel uint8

LoggerLevel is the level of the logger.

const (
	// LoggerLevelDebug defines the debug level of the logger.
	LoggerLevelDebug LoggerLevel = iota

	// LoggerLevelInfo defines the info level of the logger.
	LoggerLevelInfo

	// LoggerLevelWarn defines the warn level of the logger.
	LoggerLevelWarn

	// LoggerLevelError defines the error level of the logger.
	LoggerLevelError

	// LoggerLevelFatal defines the fatal level of the logger.
	LoggerLevelFatal

	// LoggerLevelPanic defines the panic level of the logger.
	LoggerLevelPanic

	// LoggerLevelOff defines the off level of the logger. It will turn off
	// the logger.
	LoggerLevelOff
)

The logger levels.

func (LoggerLevel) String

func (ll LoggerLevel) String() string

String returns the string value of the ll.

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.
	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.
	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.
	Authority string

	// Path is the path of the current request.
	//
	// 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.
	Path string

	// Header is the header key-value pair map of the current request.
	//
	// See RFC 7231, section 5.
	//
	// It is basically the same for both of HTTP/1.x and HTTP/2. The only
	// difference is that HTTP/2 requires header names to be lowercase. See
	// RFC 7540, section 8.1.2.
	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. 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.
	//
	// It 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.

func (*Request) Bind

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

Bind binds the r into the v.

func (*Request) ClientAddress

func (r *Request) ClientAddress() string

ClientAddress returns the original network address that sent the r.

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 the `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 `r#SetHTTPRequest()` when you have modified it.

func (*Request) LocalizedString

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

LocalizedString returns localized string for the key.

It only works if the `I18nEnabled` is true.

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 the `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 r to the r's underlying `http.Request`.

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.
	//
	// The route param value always has the highest weight.
	Values []*RequestParamValue
}

RequestParam is an HTTP request param.

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.

type RequestParamValue

type RequestParamValue struct {
	// contains filtered or unexported fields
}

RequestParamValue is an HTTP request param value.

It may represent a route path 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 rpv's underlying value.

func (*RequestParamValue) File

func (rpv *RequestParamValue) File() (*multipart.FileHeader, error)

File returns a `multipart.FileHeader` from the rpv's underlying value.

func (*RequestParamValue) Float32

func (rpv *RequestParamValue) Float32() (float32, error)

Float32 returns a `float32` from the rpv's underlying value.

func (*RequestParamValue) Float64

func (rpv *RequestParamValue) Float64() (float64, error)

Float64 returns a `float64` from the rpv's underlying value.

func (*RequestParamValue) Int

func (rpv *RequestParamValue) Int() (int, error)

Int returns an `int` from the rpv's underlying value.

func (*RequestParamValue) Int8

func (rpv *RequestParamValue) Int8() (int8, error)

Int8 returns an `int8` from the rpv's underlying value.

func (*RequestParamValue) Int16

func (rpv *RequestParamValue) Int16() (int16, error)

Int16 returns an `int16` from the rpv's underlying value.

func (*RequestParamValue) Int32

func (rpv *RequestParamValue) Int32() (int32, error)

Int32 returns an `int32` from the rpv's underlying value.

func (*RequestParamValue) Int64

func (rpv *RequestParamValue) Int64() (int64, error)

Int64 returns an `int64` from the rpv's underlying value.

func (*RequestParamValue) String

func (rpv *RequestParamValue) String() string

String returns a `string` from the rpv's underlying value.

func (*RequestParamValue) Uint

func (rpv *RequestParamValue) Uint() (uint, error)

Uint returns an `uint` from the rpv's underlying value.

func (*RequestParamValue) Uint8

func (rpv *RequestParamValue) Uint8() (uint8, error)

Uint8 returns an `uint8` from the rpv's underlying value.

func (*RequestParamValue) Uint16

func (rpv *RequestParamValue) Uint16() (uint16, error)

Uint16 returns an `uint16` from the rpv's underlying value.

func (*RequestParamValue) Uint32

func (rpv *RequestParamValue) Uint32() (uint32, error)

Uint32 returns an `uint32` from the rpv's underlying value.

func (*RequestParamValue) Uint64

func (rpv *RequestParamValue) Uint64() (uint64, error)

Uint64 returns an `uint64` from the rpv's underlying value.

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 response-line.
	//
	// For HTTP/2, it will be the ":status" pseudo-header.
	Status int

	// Header is the header key-value pair map of the current response.
	//
	// See RFC 7231, section 7.
	//
	// It is basically the same for both of HTTP/1.x and HTTP/2. The only
	// difference is that HTTP/2 requires header names to be lowercase. See
	// RFC 7540, section 8.1.2.
	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 bytes that has been written.
	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.

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 `r#SetHTTPResponseWriter()` when you have modified it.

func (*Response) ProxyPass

func (r *Response) ProxyPass(target string) error

ProxyPass passes the request to the target and responds 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 responds to the client with a redirection to the url.

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 responds to the client with the "text/html" content. 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 `r#Header`. Invalid cookies will be silently dropped.

func (*Response) SetHTTPResponseWriter

func (r *Response) SetHTTPResponseWriter(hrw http.ResponseWriter)

SetHTTPResponseWriter sets the hrw to the r's underlying `http.ResponseWriter`.

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 to the WebSocket protocol.

func (*Response) Write

func (r *Response) Write(content io.ReadSeeker) error

Write responds to the client with the content.

func (*Response) WriteFile

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

WriteFile responds to the client with a file content with the filename.

func (*Response) WriteHTML

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

WriteHTML responds to the client with the "text/html" content h.

func (*Response) WriteJSON

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

WriteJSON responds to the client with the "application/json" content v.

func (*Response) WriteMsgpack

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

WriteMsgpack responds to the client with the "application/msgpack" content v.

func (*Response) WriteProtobuf

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

WriteProtobuf responds to the client with the "application/protobuf" content v.

func (*Response) WriteString

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

WriteString responds to the client with the "text/plain" content s.

func (*Response) WriteTOML

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

WriteTOML responds to the client with the "application/toml" content v.

func (*Response) WriteXML

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

WriteXML responds to the client with the "application/xml" content v.

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)
	// contains filtered or unexported fields
}

WebSocket is a WebSocket peer.

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.

func (*WebSocket) WriteBinary

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

WriteBinary writes the b to the remote peer of the ws.

func (*WebSocket) WriteConnectionClose

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

WriteConnectionClose writes a connection close 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 to the remote peer of the ws with the appData.

func (*WebSocket) WritePong

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

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

func (*WebSocket) WriteText

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

WriteText writes the text 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