Documentation ¶
Index ¶
- Constants
- Variables
- func Env(envName string, defaultValue string) (value string)
- func MethodNotAllowedHandler(c *Context)
- func NewGracefulListener(ln net.Listener, maxWaitTime time.Duration) net.Listener
- func NotFoundHandler(c *Context)
- func Serialize(data interface{}) (bytes []byte, err error)
- type Config
- type Context
- func (c *Context) Abort()
- func (c *Context) AbortWithError(statusCode int, err error)
- func (c *Context) AbortWithStatus(statusCode int)
- func (c *Context) Bind(obj interface{}) error
- func (c *Context) BindJSON(obj interface{}) error
- func (c *Context) BindPostForm(obj interface{}) error
- func (c *Context) BindQuery(obj interface{}) error
- func (c *Context) BindXML(obj interface{}) error
- func (c *Context) Body() []byte
- func (c *Context) ClientIP() string
- func (c *Context) ContentType() string
- func (c *Context) Cookie(name string) string
- func (c *Context) Copy() *Context
- func (c *Context) Data(statusCode int, contentType string, data []byte)
- func (c *Context) Engine() *Engine
- func (c *Context) Error(msg string, statusCode int)
- func (c *Context) File(filepath string)
- func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
- func (c *Context) Get(name string) (value interface{})
- func (c *Context) GetEx(name string) (value interface{}, ok bool)
- func (c *Context) GetHeader(key string) string
- func (c *Context) HTML(statusCode int, name string, obj interface{})
- func (c *Context) Header(key, value string)
- func (c *Context) Host() string
- func (c *Context) IsAborted() bool
- func (c *Context) JS(statusCode int, name string, obj interface{})
- func (c *Context) JSON(statusCode int, obj interface{})
- func (c *Context) JSONP(statusCode int, callbackName string, obj interface{})
- func (c *Context) Method() string
- func (c *Context) MultipartForm() (*multipart.Form, error)
- func (c *Context) Next()
- func (c *Context) Param(name string) string
- func (c *Context) ParamBool(name string) bool
- func (c *Context) ParamFloat64(name string) float64
- func (c *Context) ParamInt(name string) int
- func (c *Context) ParamUint(name string) uint
- func (c *Context) Path() string
- func (c *Context) PostForm(key string) string
- func (c *Context) PostFormArray(key string) []string
- func (c *Context) PostFormArrayEx(key string) ([]string, bool)
- func (c *Context) PostFormDefault(key, defaultValue string) string
- func (c *Context) PostFormEx(key string) (string, bool)
- func (c *Context) Query(key string) string
- func (c *Context) QueryArray(key string) []string
- func (c *Context) QueryArrayEx(key string) ([]string, bool)
- func (c *Context) QueryBool(name string) bool
- func (c *Context) QueryDefault(key, defaultValue string) string
- func (c *Context) QueryEx(key string) (string, bool)
- func (c *Context) QueryFloat64(name string) float64
- func (c *Context) QueryInt(name string) int
- func (c *Context) QueryUint(name string) uint
- func (c *Context) Redirect(statusCode int, uri string)
- func (c *Context) Referer() string
- func (c *Context) RemoveCookie(name string)
- func (c *Context) RequestURI() string
- func (c *Context) SaveFormFile(name, path string) (err error)
- func (c *Context) Set(name string, value interface{})
- func (c *Context) SetContentType(contentType string)
- func (c *Context) SetCookie(name, value string, path, domain string, secure, httpOnly bool, ...)
- func (c *Context) SetStatusCode(statusCode int)
- func (c *Context) String(statusCode int, format string, values ...interface{})
- func (c *Context) URL(route string, pairs ...interface{}) string
- func (c *Context) Unset(name string)
- func (c *Context) Websocket(fn func(), bufferSizes ...int) error
- func (c *Context) WriteData(data interface{}) (err error)
- func (c *Context) XML(statusCode int, obj interface{})
- type Engine
- func (engine *Engine) HandleRequest(ctx *fasthttp.RequestCtx)
- func (engine *Engine) NotFound(handlers ...Handler)
- func (engine *Engine) Route(name string) *Route
- func (engine *Engine) Run(addr string, message ...string) error
- func (engine *Engine) RunTLS(addr string, certFile, keyFile string, message ...string) error
- func (engine *Engine) RunUnix(addr string, mode os.FileMode, message ...string) error
- func (engine *Engine) Serve(addr string, cfg *tls.Config, message ...string) error
- func (engine *Engine) Use(handlers ...Handler)
- type GracefulListener
- type Handler
- type Render
- type Route
- func (r *Route) CONNECT(handlers ...Handler) *Route
- func (r *Route) DELETE(handlers ...Handler) *Route
- func (r *Route) GET(handlers ...Handler) *Route
- func (r *Route) HEAD(handlers ...Handler) *Route
- func (r *Route) Name(name string) *Route
- func (r *Route) OPTIONS(handlers ...Handler) *Route
- func (r *Route) PATCH(handlers ...Handler) *Route
- func (r *Route) POST(handlers ...Handler) *Route
- func (r *Route) PUT(handlers ...Handler) *Route
- func (r *Route) TRACE(handlers ...Handler) *Route
- func (r *Route) To(methods string, handlers ...Handler) *Route
- func (r *Route) URL(pairs ...interface{}) (s string)
- type RouterGroup
- func (r *RouterGroup) Any(path string, handlers ...Handler) *Route
- func (r *RouterGroup) CONNECT(path string, handlers ...Handler) *Route
- func (r *RouterGroup) DELETE(path string, handlers ...Handler) *Route
- func (r *RouterGroup) GET(path string, handlers ...Handler) *Route
- func (r *RouterGroup) Group(path string, handlers ...Handler) *RouterGroup
- func (r *RouterGroup) HEAD(path string, handlers ...Handler) *Route
- func (r *RouterGroup) OPTIONS(path string, handlers ...Handler) *Route
- func (r *RouterGroup) PATCH(path string, handlers ...Handler) *Route
- func (r *RouterGroup) POST(path string, handlers ...Handler) *Route
- func (r *RouterGroup) PUT(path string, handlers ...Handler) *Route
- func (r *RouterGroup) Path() (path string)
- func (r *RouterGroup) Static(path, root string, compress ...bool) *Route
- func (r *RouterGroup) TRACE(path string, handlers ...Handler) *Route
- func (r *RouterGroup) To(methods, path string, handlers ...Handler) *Route
- func (r *RouterGroup) Use(handlers ...Handler)
- type SerializeFunc
Constants ¶
const AuthUserKey = "basicAuthUuser"
AuthUserKey is the cookie name for user credential in basic auth.
Variables ¶
var ( // AppEngine usage marker AppEngine bool // Methods lists all supported HTTP methods by Engine. Methods = []string{ "HEAD", "GET", "POST", "CONNECT", "DELETE", "OPTIONS", "PATCH", "PUT", "TRACE", } )
var ( // CookieExpireDelete may be set on Cookie.Expire for expiring the given cookie. CookieExpireDelete = fasthttp.CookieExpireDelete // CookieExpireUnlimited indicates that the cookie doesn't expire. CookieExpireUnlimited = fasthttp.CookieExpireUnlimited )
Functions ¶
func Env ¶ added in v1.0.1
Env returns environment variable value (or default value if env.variable missing)
func MethodNotAllowedHandler ¶
func MethodNotAllowedHandler(c *Context)
MethodNotAllowedHandler handles the situation when a request has matching route without matching HTTP method. In this case, the handler will respond with an Allow HTTP header listing the allowed HTTP methods. Otherwise, the handler will do nothing and let the next handler (usually a NotFoundHandler) to handle the problem.
func NewGracefulListener ¶ added in v1.4.6
NewGracefulListener wraps the given listener into 'graceful shutdown' listener.
func NotFoundHandler ¶
func NotFoundHandler(c *Context)
NotFoundHandler returns a 404 HTTP error indicating a request has no matching route.
Types ¶
type Config ¶ added in v1.2.0
type Config struct { // Print debug messages to log Debug bool // DebugFunc is callback function that calls after context DebugFunc func(*Context, time.Duration) // Extensions to parse template files from. Defaults to [".html"]. TemplatesExtensions []string // Directories to load templates. Default is ["templates"]. TemplatesDirs []string // Left templates delimiter, defaults to {{. LeftTemplateDelimiter string // Right templates delimiter, defaults to }}. RightTemplateDelimiter string // Funcs is a slice of FuncMaps to apply to the template upon compilation. This is useful for helper functions. Defaults to []. TemplatesFuncs template.FuncMap // MaxGracefulWaitTime is 'graceful shutdown' waiting duration MaxGracefulWaitTime time.Duration }
Config is a struct for specifying configuration options for the tokay.Engine object.
type Context ¶
type Context struct { *fasthttp.RequestCtx Serialize SerializeFunc // the function serializing the given data of arbitrary type into a byte array. WSConn *websocket.Conn // websocket connection // contains filtered or unexported fields }
Context represents the contextual data and environment while processing an incoming HTTP request.
func (*Context) Abort ¶
func (c *Context) Abort()
Abort skips the rest of the handlers associated with the current route. Abort is normally used when a handler handles the request normally and wants to skip the rest of the handlers. If a handler wants to indicate an error condition, it should simply return the error without calling Abort.
func (*Context) AbortWithError ¶ added in v1.0.1
AbortWithError calls `AbortWithStatus()` and `Error()` internally.
func (*Context) AbortWithStatus ¶ added in v1.0.1
AbortWithStatus calls `Abort()` and writes the headers with the specified status code. For example, a failed attempt to authenticate a request could use:
context.AbortWithStatus(401).
func (*Context) Bind ¶ added in v1.0.3
Bind checks the Content-Type to select a binding engine automatically, depending the "Content-Type" header different bindings are used.
func (*Context) BindJSON ¶ added in v1.0.3
BindJSON binds the passed struct pointer with JSON request body data
func (*Context) BindPostForm ¶ added in v1.0.3
BindPostForm binds the passed struct pointer with form data
func (*Context) BindQuery ¶ added in v1.0.3
BindQuery binds the passed struct pointer with Query data
func (*Context) BindXML ¶ added in v1.0.3
BindXML binds the passed struct pointer with XML request body data
func (*Context) Body ¶ added in v1.0.1
Body returns request body The returned body is valid until the request modification.
func (*Context) ClientIP ¶ added in v1.0.1
ClientIP returns the real client IP. It parses X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy. Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.
func (*Context) ContentType ¶ added in v1.0.1
ContentType returns the Content-Type header of the request.
func (*Context) Cookie ¶ added in v1.0.1
Cookie returns the named cookie provided in the request or ErrNoCookie if not found. And return the named cookie is unescaped. If multiple cookies match the given name, only one cookie will be returned.
func (*Context) Copy ¶ added in v1.2.3
Copy context (instance will be contain copies of Request and Response)
func (*Context) Data ¶ added in v1.0.1
Data writes some data into the body stream and updates the HTTP code.
func (*Context) Error ¶ added in v1.0.2
Error sets response status code to the given value and sets response body to the given message.
func (*Context) File ¶ added in v1.0.2
File sends local file contents from the given path as response body.
func (*Context) FormFile ¶ added in v1.0.2
func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
FormFile returns uploaded file associated with the given multipart form key. The file is automatically deleted after returning from RequestHandler, so either move or copy uploaded file into new place if you want retaining it.
Use SaveFormFile function for permanently saving uploaded file.
func (*Context) Get ¶
Get returns the named data item previously registered with the context by calling Set. If the named data item cannot be found, nil will be returned.
func (*Context) HTML ¶
HTML renders the HTTP template specified by its file name. It also updates the HTTP code and sets the Content-Type as "text/html".
func (*Context) Header ¶ added in v1.0.1
Header is a intelligent shortcut for c.Response.Header.Set(key, value). It writes a header in the response. If value == "", this method removes the header `c.Response.Header.Del(key)`
func (*Context) IsAborted ¶ added in v1.0.1
IsAborted returns true if the current context was aborted.
func (*Context) JS ¶ added in v1.2.5
JS renders the JS template specified by its file name. It also updates the HTTP code and sets the Content-Type as "text/javascript".
func (*Context) JSON ¶
JSON serializes the given struct as JSON into the response body. It also sets the Content-Type as "application/json".
func (*Context) MultipartForm ¶ added in v1.0.2
MultipartForm is the parsed multipart form, including file uploads.
func (*Context) Next ¶
func (c *Context) Next()
Next calls the rest of the handlers associated with the current route. If any of these handlers returns an error, Next will return the error and skip the following handlers. Next is normally used when a handler needs to do some postprocessing after the rest of the handlers are executed.
func (*Context) Param ¶
Param returns the named parameter value that is found in the URL path matching the current route. If the named parameter cannot be found, an empty string will be returned.
func (*Context) ParamBool ¶ added in v1.2.1
ParamBool returns the named float64 parameter value that is found in the URL path matching the current route. If the named parameter cannot be found, `false` will be returned.
func (*Context) ParamFloat64 ¶ added in v1.2.1
ParamFloat64 returns the named float64 parameter value that is found in the URL path matching the current route. If the named parameter cannot be found, .0 will be returned.
func (*Context) ParamInt ¶ added in v1.2.1
ParamInt returns the named integer parameter value that is found in the URL path matching the current route. If the named parameter cannot be found, 0 will be returned.
func (*Context) ParamUint ¶ added in v1.2.1
ParamUint returns the named uint parameter value that is found in the URL path matching the current route. If the named parameter cannot be found, 0 will be returned.
func (*Context) PostForm ¶ added in v1.0.1
PostForm returns the specified key from a POST urlencoded form or multipart form when it exists, otherwise it returns an empty string "".
func (*Context) PostFormArray ¶ added in v1.0.1
PostFormArray returns a slice of strings for a given form key. The length of the slice depends on the number of params with the given key.
func (*Context) PostFormArrayEx ¶ added in v1.0.1
PostFormArrayEx returns a slice of strings for a given form key and a boolean value whether at least one value exists for the given key.
func (*Context) PostFormDefault ¶ added in v1.0.2
PostFormDefault returns the specified key from a POST urlencoded form or multipart form when it exists, otherwise it returns the specified defaultValue string. See: PostForm() and PostFormEx() for further information.
func (*Context) PostFormEx ¶ added in v1.0.1
PostFormEx is like PostForm(key). It returns the specified key from a POST urlencoded form or multipart form when it exists `(value, true)` (even when the value is an empty string), otherwise it returns ("", false).
func (*Context) Query ¶ added in v1.0.1
Query returns the keyed url query value if it exists, otherwise it returns an empty string "".
func (*Context) QueryArray ¶ added in v1.0.1
QueryArray returns a slice of strings for a given query key. The length of the slice depends on the number of params with the given key.
func (*Context) QueryArrayEx ¶ added in v1.0.1
QueryArrayEx returns a slice of strings for a given query key, plus a boolean value whether at least one value exists for the given key.
func (*Context) QueryBool ¶ added in v1.2.1
QueryBool returns the boolean query value if it exists, otherwise it returns `false`
func (*Context) QueryDefault ¶ added in v1.0.2
QueryDefault returns the keyed url query value if it exists, otherwise it returns the specified defaultValue string. See: Query() and QueryEx() for further information.
func (*Context) QueryEx ¶ added in v1.0.1
QueryEx is like Query(), it returns the keyed url query value if it exists `(value, true)` (even when the value is an empty string), otherwise it returns `("", false)`.
func (*Context) QueryFloat64 ¶ added in v1.2.1
QueryFloat64 returns the float64 query value if it exists, otherwise it returns .0
func (*Context) QueryInt ¶ added in v1.2.1
QueryInt returns the integer query value if it exists, otherwise it returns 0
func (*Context) QueryUint ¶ added in v1.2.1
QueryUint returns the uint query value if it exists, otherwise it returns 0
func (*Context) Redirect ¶ added in v1.0.1
Redirect returns a HTTP redirect to the specific location.
func (*Context) RemoveCookie ¶ added in v1.0.2
RemoveCookie instructs the client to remove the given cookie.
func (*Context) RequestURI ¶ added in v1.0.2
RequestURI returns RequestURI.
func (*Context) SaveFormFile ¶ added in v1.0.2
SaveFormFile saves uploaded file associated with the given multipart form key under the given filename path.
func (*Context) Set ¶
Set stores the named data item in the context so that it can be retrieved later.
func (*Context) SetContentType ¶ added in v1.0.1
SetContentType sets response Content-Type.
func (*Context) SetCookie ¶ added in v1.0.1
func (c *Context) SetCookie(name, value string, path, domain string, secure, httpOnly bool, expire ...time.Time)
SetCookie adds a Set-Cookie header to the ResponseWriter's headers. The provided cookie must have a valid Name. Paramethers `path` and `domain` can be empty strings Set expiration time to CookieExpireDelete for expiring (deleting) the cookie on the client. By default cookie lifetime is limited by browser session.
func (*Context) SetStatusCode ¶ added in v1.0.1
SetStatusCode sets response status code.
func (*Context) URL ¶
URL creates a URL using the named route and the parameter values. The parameters should be given in the sequence of name1, value1, name2, value2, and so on. If a parameter in the route is not provided a value, the parameter token will remain in the resulting URL. Parameter values will be properly URL encoded. The method returns an empty string if the URL creation fails.
func (*Context) Websocket ¶ added in v1.0.5
Websocket upgrades the HTTP server connection to the WebSocket protocol.
conn, err := c.Websocket() // by default buffers size == 4096 conn, err := c.Websocket(2048) // readBufSize & writeBufSize := 2048 conn, err := c.Websocket(2048, 1024) // readBufSize := 2048, writeBufSize := 1024
type Engine ¶
type Engine struct { RouterGroup // Default render engine Render Render // AppEngine usage marker AppEngine bool // Print debug messages to log Debug bool // DebugFunc is a middleware function DebugFunc func(*Context, time.Duration) // Close server Close func() error // fasthhtp server Server *fasthttp.Server // Enables automatic redirection if the current route can't be matched but a // handler for the path with the trailing slash exists. // For example if /foo is requested but a route only exists for /foo/, the // client is redirected to /foo/ with http status code 301 for GET requests // and 307 for all other request methods. RedirectTrailingSlash bool // contains filtered or unexported fields }
Engine manages routes and dispatches HTTP requests to the handlers of the matching routes.
func (*Engine) HandleRequest ¶
func (engine *Engine) HandleRequest(ctx *fasthttp.RequestCtx)
HandleRequest handles the HTTP request.
func (*Engine) NotFound ¶
NotFound specifies the handlers that should be invoked when the engine cannot find any route matching a request. Note that the handlers registered via Use will be invoked first in this case.
func (*Engine) Route ¶
Route returns the named route. Nil is returned if the named route cannot be found.
func (*Engine) Run ¶
Run attaches the engine to a fasthttp server and starts listening and serving HTTP requests. It is a shortcut for engine.Server.ListenAndServe(addr, engine.HandleRequest) Note: this method will block the calling goroutine indefinitely unless an error happens.
func (*Engine) RunTLS ¶
RunTLS attaches the engine to a fasthttp server and starts listening and serving HTTPS (secure) requests. It is a shortcut for engine.Server.ListenAndServeTLS(addr, certFile, keyFile) Note: this method will block the calling goroutine indefinitely unless an error happens.
func (*Engine) RunUnix ¶
RunUnix attaches the engine to a fasthttp server and starts listening and serving HTTP requests through the specified unix socket (ie. a file). Note: this method will block the calling goroutine indefinitely unless an error happens.
type GracefulListener ¶ added in v1.4.6
type GracefulListener struct {
// contains filtered or unexported fields
}
GracefulListener defines a listener that we can gracefully stop
func (*GracefulListener) Accept ¶ added in v1.4.6
func (ln *GracefulListener) Accept() (net.Conn, error)
Accept creates a conn
func (*GracefulListener) Addr ¶ added in v1.4.6
func (ln *GracefulListener) Addr() net.Addr
Addr returns the listen address
func (*GracefulListener) Close ¶ added in v1.4.6
func (ln *GracefulListener) Close() (err error)
Close closes the inner listener and waits until all the pending open connections are closed before returning.
type Render ¶ added in v1.2.0
type Render interface { JSON(*fasthttp.RequestCtx, int, interface{}) error JSONP(*fasthttp.RequestCtx, int, string, interface{}) error HTML(*fasthttp.RequestCtx, int, string, interface{}, ...string) error XML(*fasthttp.RequestCtx, int, interface{}) error JS(*fasthttp.RequestCtx, int, string, interface{}, ...string) error }
Render is interface for engine.Render
type Route ¶
type Route struct {
// contains filtered or unexported fields
}
Route represents a URL path pattern that can be used to match requested URLs.
func (*Route) Name ¶
Name sets the name of the route. This method will update the registration of the route in the engine as well.
func (*Route) To ¶
To adds the route to the engine with the given HTTP methods and handlers. Multiple HTTP methods should be separated by commas (without any surrounding spaces).
func (*Route) URL ¶
URL creates a URL using the current route and the given parameters. The parameters should be given in the sequence of name1, value1, name2, value2, and so on. If a parameter in the route is not provided a value, the parameter token will remain in the resulting URL. The method will perform URL encoding for all given parameter values.
type RouterGroup ¶
type RouterGroup struct {
// contains filtered or unexported fields
}
RouterGroup represents a group of routes that share the same path prefix.
func (*RouterGroup) Any ¶
func (r *RouterGroup) Any(path string, handlers ...Handler) *Route
Any adds a route with the given route, handlers, and the HTTP methods as listed in routing.Methods.
func (*RouterGroup) CONNECT ¶
func (r *RouterGroup) CONNECT(path string, handlers ...Handler) *Route
CONNECT adds a CONNECT route to the engine with the given route path and handlers.
func (*RouterGroup) DELETE ¶
func (r *RouterGroup) DELETE(path string, handlers ...Handler) *Route
DELETE adds a DELETE route to the engine with the given route path and handlers.
func (*RouterGroup) GET ¶
func (r *RouterGroup) GET(path string, handlers ...Handler) *Route
GET adds a GET route to the engine with the given route path and handlers.
func (*RouterGroup) Group ¶
func (r *RouterGroup) Group(path string, handlers ...Handler) *RouterGroup
Group creates a RouterGroup with the given route path and handlers. The new group will combine the existing path with the new one. If no handler is provided, the new group will inherit the handlers registered with the current group.
func (*RouterGroup) HEAD ¶
func (r *RouterGroup) HEAD(path string, handlers ...Handler) *Route
HEAD adds a HEAD route to the engine with the given route path and handlers.
func (*RouterGroup) OPTIONS ¶
func (r *RouterGroup) OPTIONS(path string, handlers ...Handler) *Route
OPTIONS adds an OPTIONS route to the engine with the given route path and handlers.
func (*RouterGroup) PATCH ¶
func (r *RouterGroup) PATCH(path string, handlers ...Handler) *Route
PATCH adds a PATCH route to the engine with the given route path and handlers.
func (*RouterGroup) POST ¶
func (r *RouterGroup) POST(path string, handlers ...Handler) *Route
POST adds a POST route to the engine with the given route path and handlers.
func (*RouterGroup) PUT ¶
func (r *RouterGroup) PUT(path string, handlers ...Handler) *Route
PUT adds a PUT route to the engine with the given route path and handlers.
func (*RouterGroup) Path ¶ added in v1.0.5
func (r *RouterGroup) Path() (path string)
Path returns RouterGroup fullpath
func (*RouterGroup) Static ¶
func (r *RouterGroup) Static(path, root string, compress ...bool) *Route
Static serves files from the given file system root. Where: 'path' - relative path from current engine path on site (must be without trailing slash), 'root' - directory that contains served files. For example:
engine.Static("/static", "/var/www")
func (*RouterGroup) TRACE ¶
func (r *RouterGroup) TRACE(path string, handlers ...Handler) *Route
TRACE adds a TRACE route to the engine with the given route path and handlers.
func (*RouterGroup) To ¶
func (r *RouterGroup) To(methods, path string, handlers ...Handler) *Route
To adds a route to the engine with the given HTTP methods, route path, and handlers. Multiple HTTP methods should be separated by commas (without any surrounding spaces).
func (*RouterGroup) Use ¶
func (r *RouterGroup) Use(handlers ...Handler)
Use registers one or multiple handlers to the current route group. These handlers will be shared by all routes belong to this group and its subgroups.
type SerializeFunc ¶
SerializeFunc serializes the given data of arbitrary type into a byte array.