air

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2017 License: Unlicense Imports: 34 Imported by: 0

README

Air

Build Status codecov Go Report Card GoDoc

An ideal RESTful web framework for Go. You can use it to develop a RESTful 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. This framework does not intend to follow the crowd. So, Air web framework can only guarantee you one thing: it can serve properly.

Features

  • APIs
    • As less as possible.
    • As simple as possible.
    • As expressive as possible.
  • HTTP Methods (only four)
    • GET
    • POST
    • PUT
    • DELETE
  • Server
    • HTTP/2 support.
    • SSL/TLS support.
    • Gracefully shutdown support.
    • Powered by the Go net/http.
  • Router
    • Based on the Radix Tree.
    • Zero dynamic memory allocation.
    • Has a good inspection mechanism.
    • Group routes support.
  • Gas (also called middleware)
    • Router level:
      • Before router.
      • After router.
    • Route level.
    • Group level.
  • Config
    • For server.
    • For logger.
    • For renderer.
    • For coffer.
    • For everything.
    • Configuration file support by using the toml.
  • Logger
    • Customizable.
    • Default implementation:
      • Powered by the Go text/template.
  • Binder
    • Customizable.
    • Default implementation:
      • Based on the Content-Type header.
      • Supported MIME types:
        • application/json.
        • application/xml.
        • application/x-www-form-urlencoded.
  • Minifier
    • Customizable.
    • Default implementation:
      • Supported MIME types:
        • text/html
        • text/css
        • text/javascript
        • application/json
        • text/xml
        • image/jpeg
        • image/png
        • image/svg+xml
      • Powered by the Go image and the minify.
  • Renderer
    • Customizable.
    • Default implementation:
      • Rich template functions.
      • Hot update support by using the fsnotify.
      • Powered by the Go html/template.
  • Coffer
    • Customizable.
    • Accesses binary asset files by using the runtime memory.
    • Reduces the hard disk I/O and significantly improves the performance of the Response#File().
    • Default implementation:
      • Asset file minimization:
        • .html
        • .css
        • .js
        • .json
        • .xml
        • .svg
      • Hot update support by using the fsnotify.
  • HTTPError
    • Customizable.
    • Centralized handling.

Installation

Open your terminal and execute

$ go get github.com/sheng/air

done.

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

Hello, 世界

Create a file named hello.go

package main

import "github.com/sheng/air"

func main() {
	a := air.New()
	a.GET("/", homeHandler)
	a.Serve()
}

func homeHandler(c *air.Context) error {
	return c.String("Hello, 世界")
}

and run it

$ go run hello.go

then visit http://localhost:2333.

Documentation

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.

If you want to learn more about the gases, or create your own gas for this framework, 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 these to send pull requests here.

License

This project is licensed under the Unlicense.

License can be found here.

Documentation

Index

Constants

View Source
const (
	MIMEApplicationJSON               = "application/json"
	MIMEApplicationJavaScript         = "application/javascript"
	MIMEApplicationXML                = "application/xml"
	MIMEApplicationXWWWFormURLEncoded = "application/x-www-form-urlencoded"
	MIMEImageJPEG                     = "image/jpeg"
	MIMEImagePNG                      = "image/png"
	MIMEImageSVGXML                   = "image/svg+xml"
	MIMEMultipartFormData             = "multipart/form-data"
	MIMETextCSS                       = "text/css"
	MIMETextHTML                      = "text/html"
	MIMETextJavaScript                = "text/javascript"
	MIMETextPlain                     = "text/plain"
	MIMETextXML                       = "text/xml"

	CharsetUTF8 = "; charset=utf-8"
)

MIME types

View Source
const (
	GET    = "GET"
	POST   = "POST"
	PUT    = "PUT"
	DELETE = "DELETE"
)

HTTP methods

View Source
const (
	HeaderAccept                          = "Accept"
	HeaderAcceptCharset                   = "Accept-Charset"
	HeaderAcceptEncoding                  = "Accept-Encoding"
	HeaderAcceptLanguage                  = "Accept-Language"
	HeaderAcceptRanges                    = "Accept-Ranges"
	HeaderAccessControlAllowCredentials   = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders       = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods       = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin        = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders      = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge             = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders     = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod      = "Access-Control-Request-Method"
	HeaderAge                             = "Age"
	HeaderAllow                           = "Allow"
	HeaderAuthorization                   = "Authorization"
	HeaderCacheControl                    = "Cache-Control"
	HeaderConnection                      = "Connection"
	HeaderContentDisposition              = "Content-Disposition"
	HeaderContentEncoding                 = "Content-Encoding"
	HeaderContentLanguage                 = "Content-Language"
	HeaderContentLength                   = "Content-Length"
	HeaderContentLocation                 = "Content-Location"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderContentType                     = "Content-Type"
	HeaderCookie                          = "Cookie"
	HeaderDNT                             = "DNT"
	HeaderDate                            = "Date"
	HeaderETag                            = "ETag"
	HeaderExpires                         = "Expires"
	HeaderForm                            = "Form"
	HeaderHost                            = "Host"
	HeaderIfMatch                         = "If-Match"
	HeaderIfModifiedSince                 = "If-Modified-Since"
	HeaderIfNoneMatch                     = "If-None-Match"
	HeaderIfRange                         = "If-Range"
	HeaderIfUnmodifiedSince               = "If-Unmodified-Since"
	HeaderKeepAlive                       = "Keep-Alive"
	HeaderLastModified                    = "Last-Modified"
	HeaderLocation                        = "Location"
	HeaderOrigin                          = "Origin"
	HeaderPublicKeyPins                   = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly         = "Public-Key-Pins-Report-Only"
	HeaderReferer                         = "Referer"
	HeaderReferrerPolicy                  = "Referrer-Policy"
	HeaderRetryAfter                      = "Retry-After"
	HeaderServer                          = "Server"
	HeaderSetCookie                       = "Set-Cookie"
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderTE                              = "TE"
	HeaderTK                              = "TK"
	HeaderTrailer                         = "Trailer"
	HeaderTransferEncoding                = "Transfer-Encoding"
	HeaderUpgrade                         = "Upgrade"
	HeaderUpgradeInsecureRequests         = "Upgrade-Insecure-Requests"
	HeaderUserAgent                       = "User-Agent"
	HeaderVary                            = "Vary"
	HeaderVia                             = "Via"
	HeaderWWWAuthenticate                 = "WWW-Authenticate"
	HeaderWarning                         = "Warning"
	HeaderXCSRFToken                      = "X-CSRF-Token"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXDNSPrefetchControl             = "X-DNS-Prefetch-Control"
	HeaderXForwardedFor                   = "X-Forwarded-For"
	HeaderXForwardedProto                 = "X-Forwarded-Proto"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderXHTTPMethodOverride             = "X-HTTP-Method-Override"
	HeaderXRealIP                         = "X-Real-IP"
	HeaderXXSSProtection                  = "X-XSS-Protection"
)

HTTP headers

Variables

View Source
var (
	ErrUnauthorized                = NewHTTPError(http.StatusUnauthorized)          // 401
	ErrNotFound                    = NewHTTPError(http.StatusNotFound)              // 404
	ErrMethodNotAllowed            = NewHTTPError(http.StatusMethodNotAllowed)      // 405
	ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge) // 413
	ErrUnsupportedMediaType        = NewHTTPError(http.StatusUnsupportedMediaType)  // 415

	ErrInternalServerError = NewHTTPError(http.StatusInternalServerError) // 500
	ErrBadGateway          = NewHTTPError(http.StatusBadGateway)          // 502
	ErrServiceUnavailable  = NewHTTPError(http.StatusServiceUnavailable)  // 503
	ErrGatewayTimeout      = NewHTTPError(http.StatusGatewayTimeout)      // 504

	ErrInvalidRedirectCode = errors.New("invalid redirect status code")
)

HTTP errors

View Source
var (
	NotFoundHandler = func(c *Context) error {
		return ErrNotFound
	}

	MethodNotAllowedHandler = func(c *Context) error {
		return ErrMethodNotAllowed
	}
)

HTTP error handlers

View Source
var DefaultConfig = Config{
	AppName: "air",
	LogFormat: `{"app_name":"{{.app_name}}","time":"{{.time_rfc3339}}","level":"{{.level}}",` +
		`"file":"{{.short_file}}","line":"{{.line}}"}`,
	Address:            "localhost:2333",
	MaxHeaderBytes:     1 << 20,
	TemplateRoot:       "templates",
	TemplateExts:       []string{".html"},
	TemplateLeftDelim:  "{{",
	TemplateRightDelim: "}}",
	AssetRoot:          "assets",
	AssetExts:          []string{".html", ".css", ".js", ".json", ".xml", ".svg"},
}

DefaultConfig is the default instance of the `Config`.

Functions

func DefaultHTTPErrorHandler

func DefaultHTTPErrorHandler(err error, c *Context)

DefaultHTTPErrorHandler is the default HTTP error handler.

Types

type Air

type Air struct {
	Config           *Config
	Logger           Logger
	Binder           Binder
	Minifier         Minifier
	Renderer         Renderer
	Coffer           Coffer
	HTTPErrorHandler HTTPErrorHandler
	// contains filtered or unexported fields
}

Air is the top-level framework struct.

func New

func New() *Air

New returns a pointer of a new instance of the `Air`.

func (*Air) Close

func (a *Air) Close() error

Close closes the HTTP server immediately.

func (*Air) Contain

func (a *Air) Contain(gases ...Gas)

Contain adds the gases to the chain which is perform after the router.

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

func (a *Air) File(path, file string)

File registers a new route with the path to serve a static file.

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

func (a *Air) Precontain(gases ...Gas)

Precontain adds the gases to the chain which is perform before the router.

func (*Air) Serve

func (a *Air) Serve() error

Serve starts the HTTP server.

func (*Air) Shutdown

func (a *Air) Shutdown(c *Context) error

Shutdown gracefully shuts down the HTTP server without interrupting any active connections.

func (*Air) Static

func (a *Air) Static(prefix, root string)

Static registers a new route with the path prefix to serve the static files from the provided root directory.

func (*Air) URL

func (a *Air) URL(h Handler, params ...interface{}) string

URL returns an URL generated from the h with the optional params.

type Asset

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

Asset is a binary asset file.

func NewAsset

func NewAsset(name string, modTime time.Time, content []byte) *Asset

NewAsset returns a pointer of a new instance of the `Asset`.

func (*Asset) ModTime

func (a *Asset) ModTime() time.Time

ModTime returns the modTime of the a.

func (*Asset) Name

func (a *Asset) Name() string

Name returns the name of the a.

func (*Asset) Read

func (a *Asset) Read(b []byte) (int, error)

Read implements the `io.Reader`.

func (*Asset) Seek

func (a *Asset) Seek(offset int64, whence int) (int64, error)

Seek implements the `io.Seeker`.

type Binder

type Binder interface {
	// Bind binds the body of the req into the provided type i.
	Bind(i interface{}, req *Request) error
}

Binder is used to provide a `Bind()` method for an `Air` instance for binds an HTTP request body into privided type.

type Coffer

type Coffer interface {
	// Init initializes the `Coffer`. It will be called in the `Air#Serve()`.
	Init() error

	// Asset returns an `Asset` in the `Coffer` for the provided name.
	//
	// **Please use the `filepath.Abs()` to process the name before calling.**
	Asset(name string) *Asset
}

Coffer is used to provide an `Asset()` method for an `Air` instance for accesses binary asset files by using the runtime memory.

type Config

type Config struct {
	// AppName represents the name of the `Air` instance.
	//
	// The default Value is "air".
	//
	// It's called "app_name" in the config file.
	AppName string

	// DebugMode indicates whether to enable the debug mode when the HTTP server is started.
	//
	// The default value is false.
	//
	// It's called "debug_mode" in the config file.
	DebugMode bool

	// LoggerEnabled indicates whether to enable the `Logger` when the HTTP server is started.
	// It works only with the default `Logger`.
	//
	// It will be forced to the true if the `DebugMode` is true.
	//
	// The default value is false.
	//
	// It's called "logger_enabled" in the config file.
	LoggerEnabled bool

	// LogFormat represents the format of the output content of the `Logger`. It works only with
	// the default `Logger` and when the `LoggerEnabled` is true.
	//
	// The default value is:
	// `{"app_name":"{{.app_name}}","time":"{{.time_rfc3339}}","level":"{{.level}}",` +
	// `"file":"{{.short_file}}","line":"{{.line}}"}`
	//
	// It's called "log_format" in the config file.
	LogFormat string

	// Address represents the TCP address that the HTTP server to listen on.
	//
	// The default value is "localhost:2333".
	//
	// It's called "address" in the config file.
	Address string

	// ReadTimeout represents the maximum duration before timing out read of the HTTP request.
	//
	// The default value is 0.
	//
	// It's called "read_timeout" in the config file.
	//
	// **It's unit in the config file is MILLISECONDS.**
	ReadTimeout time.Duration

	// WriteTimeout represents the maximum duration before timing out write of the HTTP
	// response.
	//
	// The default value is 0.
	//
	// It's called "write_timeout" in the config file.
	//
	// **It's unit in the config file is MILLISECONDS.**
	WriteTimeout time.Duration

	// MaxHeaderBytes represents the maximum number of bytes the HTTP server will read parsing
	// the HTTP request header's keys and values, including the HTTP request line. It does not
	// limit the size of the HTTP request body.
	//
	// The default value is 1048576.
	//
	// It's called "max_header_bytes" in the config file.
	MaxHeaderBytes int

	// TLSCertFile represents the path of the TLS certificate file.
	//
	// The default value is "".
	//
	// It's called "tls_cert_file" in the config file.
	TLSCertFile string

	// TLSKeyFile represents the path of the TLS key file.
	//
	// The default value is "".
	//
	// It's called "tls_key_file" in the config file.
	TLSKeyFile string

	// TemplateRoot represents the root directory of the HTML templates. It will be parsed into
	// the `Renderer`. It works only with the default `Renderer`.
	//
	// The default value is "templates" that means a subdirectory of the runtime directory.
	//
	// It's called "template_root" in the config file.
	TemplateRoot string

	// TemplateExts represents the file name extensions of the HTML templates. It will be used
	// when parsing the HTML templates. It works only with the default `Renderer`.
	//
	// The default value is [".html"].
	//
	// It's called "template_exts" in the config file.
	TemplateExts []string

	// TemplateLeftDelim represents the left side of the HTML template delimiter. It will be
	// used when parsing the HTML templates. It works only with the default `Renderer`.
	//
	// The default value is "{{".
	//
	// It's called "template_left_delim" in the config file.
	TemplateLeftDelim string

	// TemplateRightDelim represents the right side of the HTML template delimiter. It will be
	// used when parsing the HTML templates. It works only with the default `Renderer`.
	//
	// The default value is "}}".
	//
	// It's called "template_right_delim" in the config file.
	TemplateRightDelim string

	// TemplateMinified indicates whether to minify the HTML templates before they being parsed
	// into the `Renderer`. It works only with the default `Renderer`.
	//
	// The default value is false.
	//
	// It's called "template_minified" in the config file.
	TemplateMinified bool

	// CofferEnabled indicates whether to enable the `Coffer` when the HTTP server is started.
	// It works only with the default `Coffer`.
	//
	// The default value is false.
	//
	// It's called "coffer_enabled" in the config file.
	CofferEnabled bool

	// AssetRoot represents the root directory of the asset files. It will be loaded into the
	// `Coffer`. It works only with the default `Coffer` and when the `CofferEnabled` is true.
	//
	// The default value is "assets" that means a subdirectory of the runtime directory.
	//
	// It's called "asset_root" in the config file.
	AssetRoot string

	// AssetExts represents the file name extensions of the asset files. It will be used when
	// loading the asset files. It works only with the default `Coffer` and when the
	// `CofferEnabled` is true.
	//
	// The default value is [".html", ".css", ".js", ".json", ".xml", ".svg"].
	//
	// It's called "asset_exts" in the config file.
	AssetExts []string

	// AssetMinified indicates whether to minify the asset files before they being loaded into
	// the `Coffer`. It works only with the default `Coffer` and when the `CofferEnabled` is
	// true.
	//
	// The default value is false.
	//
	// It's called "asset_minified" in the config file.
	AssetMinified bool

	// Data represents the data that parsing from the config file. You can use it to access the
	// values in the config file.
	//
	// e.g. Data["foobar"] will accesses the value in the config file called "foobar".
	Data Map
}

Config is a global set of configs that for an instance of the `Air` for customization.

func NewConfig

func NewConfig(filename string) *Config

NewConfig returns a pointer of a new instance of the `Config` by parsing the config file found in the filename path. It returns a copy of the DefaultConfig if the config file does not exist.

func (*Config) Parse

func (c *Config) Parse(src string) error

Parse parses the src into the c.

func (*Config) ParseFile

func (c *Config) ParseFile(filename string) error

ParseFile parses the config file found in the filename path into the c.

type Context

type Context struct {
	context.Context

	Air *Air

	Request  *Request
	Response *Response

	PristinePath string
	ParamNames   []string
	ParamValues  []string
	Handler      Handler

	// Cancel is non-nil if one of the `SetCancel()`, the `SetDeadline()` or the `SetTimeout()`
	// is called. It will be called when the HTTP server finishes the current cycle if it is
	// non-nil and has never been called.
	Cancel context.CancelFunc

	// Data is an alias for the `Response#Data`.
	Data Map
}

Context represents the context of the current HTTP request.

It's embedded with the `context.Context`.

func NewContext

func NewContext(a *Air) *Context

NewContext returns a pointer of a new instance of the `Context`.

func (*Context) Attachment

func (c *Context) Attachment(file, filename string) error

Attachment is an alias for the `Response#Attachment()` of the c.

func (*Context) Bind

func (c *Context) Bind(i interface{}) error

Bind is an alias for the `Request#Bind()` of the c.

func (*Context) Blob

func (c *Context) Blob(contentType string, b []byte) error

Blob is an alias for the `Response#Blob()` of the c.

func (*Context) Cookie

func (c *Context) Cookie(name string) (*http.Cookie, error)

Cookie is an alias for the `Request#Cookie()` of the c.

func (*Context) Cookies

func (c *Context) Cookies() []*http.Cookie

Cookies is an alias for the `Request#Cookies()` of the c.

func (*Context) File

func (c *Context) File(file string) error

File is an alias for the `Response#File()` of the c.

func (*Context) FormFile

func (c *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

FormFile is an alias for the `Request#FormFile()` of the c.

func (*Context) FormValue

func (c *Context) FormValue(key string) string

FormValue is an alias for the `Request#FormValue()` of the c.

func (*Context) FormValues

func (c *Context) FormValues() url.Values

FormValues is an alias for the `Request#FormValues()` of the c.

func (*Context) HTML

func (c *Context) HTML(html string) error

HTML is an alias for the `Response#HTML()` of the c.

func (*Context) HasFormValue

func (c *Context) HasFormValue(key string) bool

HasFormValue is an alias for the `Request#HasFormValue()` of the c.

func (*Context) HasQueryValue

func (c *Context) HasQueryValue(key string) bool

HasQueryValue is an alias for the `Request#HasQueryValue()` of the c.

func (*Context) Inline

func (c *Context) Inline(file, filename string) error

Inline is an alias for the `Response#Inline()` of the c.

func (*Context) JSON

func (c *Context) JSON(i interface{}) error

JSON is an alias for the `Response#JSON()` of the c.

func (*Context) JSONP

func (c *Context) JSONP(i interface{}, callback string) error

JSONP is an alias for the `Response#JSONP()` of the c.

func (*Context) NoContent

func (c *Context) NoContent() error

NoContent is an alias for the `Response#NoContent()` of the c.

func (*Context) Param

func (c *Context) Param(name string) string

Param returns the path param value by the name.

func (*Context) Push

func (c *Context) Push(target string, pos *http.PushOptions) error

Push is an alias for the `Response#Push()` of the c.

func (*Context) QueryValue

func (c *Context) QueryValue(key string) string

QueryValue is an alias for the `Request#QueryValue()` of the c.

func (*Context) QueryValues

func (c *Context) QueryValues() url.Values

QueryValues is an alias for the `Request#QueryValues()` of the c.

func (*Context) Redirect

func (c *Context) Redirect(statusCode int, url string) error

Redirect is an alias for the `Response#Redirect()` of the c.

func (*Context) Render

func (c *Context) Render(templates ...string) error

Render is an alias for the `Response#Render()` of the c.

func (*Context) SetCancel

func (c *Context) SetCancel()

SetCancel sets a new done channel into the `Context` of the c.

func (*Context) SetCookie

func (c *Context) SetCookie(cookie *http.Cookie)

SetCookie is an alias for the `Response#SetCookie()` of the c.

func (*Context) SetDeadline

func (c *Context) SetDeadline(deadline time.Time)

SetDeadline sets a new deadline into the `Context` of the c.

func (*Context) SetTimeout

func (c *Context) SetTimeout(timeout time.Duration)

SetTimeout sets a new deadline based on the timeout into the `Context` of the c.

func (*Context) SetValue

func (c *Context) SetValue(key interface{}, val interface{})

SetValue sets request-scoped value into the `Context` of the c.

func (*Context) Stream

func (c *Context) Stream(contentType string, r io.Reader) error

Stream is an alias for the `Response#Stream()` of the c.

func (*Context) String

func (c *Context) String(s string) error

String is an alias for the `Response#String()` of the c.

func (*Context) XML

func (c *Context) XML(i interface{}) error

XML is an alias for the `Response#XML()` of the c.

type Gas

type Gas func(Handler) Handler

Gas defines a function to process gases.

func WrapGas

func WrapGas(h Handler) Gas

WrapGas wraps the h into the `Gas`.

type Group

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

Group is a set of sub-routes for a specified route. It can be used for inner routes that share a common gas or functionality that should be separate from the parent `Air` instance while still inheriting from it.

func NewGroup

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

NewGroup returns a pointer of a new router group with the prefix and the optional group-level gases.

func (*Group) Contain

func (g *Group) Contain(gases ...Gas)

Contain implements the `Air#Contain()`.

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)

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

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

NewSubGroup creates a pointer of a new sub-group with the prefix and the optional sub-group-level gases.

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)

Static implements the `Air#Static()`.

type HTTPError

type HTTPError struct {
	Code    int
	Message string
}

HTTPError represents an error that occurred while handling an HTTP request.

func NewHTTPError

func NewHTTPError(code int, messages ...interface{}) *HTTPError

NewHTTPError returns a pointer of a new instance of the `HTTPError`.

func (*HTTPError) Error

func (he *HTTPError) Error() string

Error implements the `error#Error()`.

type HTTPErrorHandler

type HTTPErrorHandler func(error, *Context)

HTTPErrorHandler is a centralized HTTP error handler.

type Handler

type Handler func(*Context) error

Handler defines a function to serve HTTP requests.

func WrapHandler

func WrapHandler(h http.Handler) Handler

WrapHandler wraps the h into the `Handler`.

type Logger

type Logger interface {
	// Output returns the output of the `Logger`.
	Output() io.Writer

	// SetOutput sets the w to the output of the `Logger`.
	SetOutput(w io.Writer)

	// Print prints the log info with the provided type i.
	Print(i ...interface{})

	// Printf prints the log info in the format with the provided args.
	Printf(format string, args ...interface{})

	// Printj prints the log info in the JSON format with the provided m.
	Printj(m Map)

	// Debug prints the DEBUG level log info with the provided type i.
	Debug(i ...interface{})

	// Debugf prints the DEBUG level log info in the format with the provided args.
	Debugf(format string, args ...interface{})

	// Debugj prints the DEBUG level log info in the JSON format with the provided m.
	Debugj(m Map)

	// Info prints the INFO level log info with the provided type i.
	Info(i ...interface{})

	// Infof prints the INFO level log info in the format with the provided args.
	Infof(format string, args ...interface{})

	// Infoj prints the INFO level log info in the JSON format with the provided m.
	Infoj(m Map)

	// Warn prints the WARN level log info with the provided type i.
	Warn(i ...interface{})

	// Warnf prints the WARN level log info in the format with the provided args.
	Warnf(format string, args ...interface{})

	// Warnj prints the WARN level log info in the JSON format with the provided m.
	Warnj(m Map)

	// Error prints the ERROR level log info with the provided type i.
	Error(i ...interface{})

	// Errorf prints the ERROR level log info in the format with the provided args.
	Errorf(format string, args ...interface{})

	// Errorj prints the ERROR level log info in the JSON format with the provided m.
	Errorj(m Map)

	// Fatal prints the FATAL level log info with the provided type i.
	Fatal(i ...interface{})

	// Fatalf prints the FATAL level log info in the format with the provided args.
	Fatalf(format string, args ...interface{})

	// Fatalj prints the FATAL level log info in the JSON format with the provided m.
	Fatalj(m Map)
}

Logger is used to log information generated in the runtime.

type Map

type Map map[string]interface{}

Map is the `map[string]interface{}`.

type Minifier

type Minifier interface {
	// Init initializes the `Minifier`. It will be called in the `Air#Serve()`.
	Init() error

	// Minify minifies the b by the mimeType.
	Minify(mimeType string, b []byte) ([]byte, error)
}

Minifier is used to provide a `Minify()` method for an `Air` instance for minifies a content by a MIME type.

type Renderer

type Renderer interface {
	// Init initializes the `Renderer`. It will be called in the `Air#Serve()`.
	Init() error

	// SetTemplateFunc sets the func f into the `Renderer` with the name.
	SetTemplateFunc(name string, f interface{})

	// Render renders the data into the w with the templateName.
	Render(w io.Writer, templateName string, data Map) error
}

Renderer is used to provide a `Render()` method for an `Air` instance for renders a "text/html" HTTP response.

type Request

type Request struct {
	*http.Request

	URL *URL
	// contains filtered or unexported fields
}

Request represents the current HTTP request.

It's embedded with the `http.Request`.

func NewRequest

func NewRequest(c *Context) *Request

NewRequest returns a pointer of a new instance of the `Request`.

func (*Request) Bind

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

Bind binds the HTTP body of the r into the provided type i. The default `Binder` does it based on the "Content-Type" header.

func (*Request) FormValues

func (r *Request) FormValues() url.Values

FormValues returns the form values.

func (*Request) HasFormValue

func (r *Request) HasFormValue(key string) bool

HasFormValue reports whether the form values contains the form value for the provided key.

func (*Request) HasQueryValue

func (r *Request) HasQueryValue(key string) bool

HasQueryValue is an alias for the `URL#HasQueryValue()` of the r.

func (*Request) QueryValue

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

QueryValue is an alias for the `URL#QueryValue()` of the r.

func (*Request) QueryValues

func (r *Request) QueryValues() url.Values

QueryValues is an alias for the `URL#QueryValues()` of the r.

type Response

type Response struct {
	http.ResponseWriter
	http.Hijacker
	http.CloseNotifier
	http.Flusher
	http.Pusher

	StatusCode int
	Size       int
	Written    bool
	Data       Map
	// contains filtered or unexported fields
}

Response represents the current HTTP response.

It's embedded with the `http.ResponseWriter`, the `http.Hijacker`, the `http.CloseNotifier`, the `http.Flusher` and the `http.Pusher`.

func NewResponse

func NewResponse(c *Context) *Response

NewResponse returns a pointer of a new instance of the `Response`.

func (*Response) Attachment

func (r *Response) Attachment(file, filename string) error

Attachment sends an HTTP response with the file and the filename as attachment, prompting client to save the file.

func (*Response) Blob

func (r *Response) Blob(contentType string, b []byte) error

Blob sends a blob HTTP response with the contentType and the b.

func (*Response) File

func (r *Response) File(file string) error

File sends a file HTTP response with the file.

func (*Response) HTML

func (r *Response) HTML(html string) error

HTML sends a "text/html" HTTP response with the html.

func (*Response) Inline

func (r *Response) Inline(file, filename string) error

Inline sends an HTTP response with the file and the filename as inline, opening the file in the browser.

func (*Response) JSON

func (r *Response) JSON(i interface{}) error

JSON sends an "application/json" HTTP response with the type i.

func (*Response) JSONP

func (r *Response) JSONP(i interface{}, callback string) error

JSONP sends an "application/javascript" HTTP response with the type i. It uses the callback to construct the JSONP payload.

func (*Response) NoContent

func (r *Response) NoContent() error

NoContent sends an HTTP response with no body.

func (*Response) Redirect

func (r *Response) Redirect(statusCode int, url string) error

Redirect redirects the current HTTP request to the url with the statusCode.

func (*Response) Render

func (r *Response) Render(templates ...string) error

Render renders one or more HTML templates with the `Data` of the r and sends a "text/html" HTTP response. The default `Renderer` does it by using the `template.Template`. the rults rendered by the former can be inherited by accessing the `Data["InheritedHTML"]` of the r.

func (*Response) SetCookie

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

SetCookie adds a "Set-Cookie" header in the r. The provided cookie must have a valid `Name`. Invalid cookies may be silently dropped.

func (*Response) Stream

func (r *Response) Stream(contentType string, reader io.Reader) error

Stream sends a streaming HTTP response with the contentType and the reader.

func (*Response) String

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

String sends a "text/plain" HTTP response with the s.

func (*Response) Write

func (r *Response) Write(b []byte) (int, error)

Write implements the `http.ResponseWriter#Write()`.

func (*Response) WriteHeader

func (r *Response) WriteHeader(statusCode int)

WriteHeader implements the `http.ResponseWriter#WriteHeader()`.

func (*Response) XML

func (r *Response) XML(i interface{}) error

XML sends an "application/xml" HTTP response with the type i.

type URL

type URL struct {
	*url.URL
	// contains filtered or unexported fields
}

URL represents the HTTP URL of the current HTTP request.

It's embedded with the `url.URL`.

func NewURL

func NewURL(r *Request) *URL

NewURL returns a pointer of a new instance of the `URL`.

func (*URL) HasQueryValue

func (u *URL) HasQueryValue(key string) bool

HasQueryValue reports whether the query values contains the query value for the provided key.

func (*URL) QueryValue

func (u *URL) QueryValue(key string) string

QueryValue returns the query value in the u for the provided key.

func (*URL) QueryValues

func (u *URL) QueryValues() url.Values

QueryValues returns the query values in the u.

Jump to

Keyboard shortcuts

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