tokay

package module
v1.4.8 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2023 License: BSD-3-Clause Imports: 30 Imported by: 8

README

Tokay

GoDoc Go Report github issues github closed issues release

Description

Tokay is small and fast web framework written in Go (Golang) for the high-performance fasthttp server. The package has the following features:

  • middleware pipeline architecture, similar to that of the Gin-gonic framework.
  • extremely fast request routing with zero dynamic memory allocation
  • modular code organization through route grouping
  • flexible URL path matching, supporting URL parameters and regular expressions
  • URL creation according to the predefined routes
  • HTML, XML, JSON etc. rendering based on package night-codes/tokay-render

Requirements

Go 1.13 or above.

Installation

Run the following command to install the package:

go get github.com/night-codes/tokay

Getting Started

Create a server.go file with the following content:

package main

import (
	"github.com/night-codes/tokay"
)

func main() {
	app := tokay.New()

	// Methods:   GET, POST
	// Resource: http://localhost:8080/
	app.To("GET,POST", "/", func(c *tokay.Context) {
		c.String(200, "Hello world!")
	})

	// same as app.To("GET", "/ping", [...])
	// Method:   GET
	// Resource: http://localhost:8080/ping
	app.GET("/ping", func(c *tokay.Context) {
		c.String(200, "pong")
	})

	// Method:   GET
	// Resource: http://localhost:8080/hello
	app.GET("/hello", func(c *tokay.Context) {
		c.JSON(200, map[string]interface{}{"message": "Hello world!"})
	})

	// http://localhost:8080
	// http://localhost:8080/ping
	// http://localhost:8080/hello
	app.Run(":8080", "Application started at http://localhost%s")
}

Now run the following command to start the Web server:

go run server.go

You should be able to access URLs such as http://localhost:8080.

Routes

Routing works by building a routing table in a router and then dispatching HTTP requests to the matching handlers found in the routing table. An intuitive illustration of a routing table is as follows:

Routes Handlers
GET /users m1, m2, h1, ...
POST /users m1, m2, h2, ...
PUT /users/<id> m1, m2, h3, ...
DELETE /users/<id> m1, m2, h4, ...

For an incoming request GET /users, the first route would match and the handlers m1, m2, and h1 would be executed. If the request is PUT /users/123, the third route would match and the corresponding handlers would be executed. Note that the token <id> can match any number of non-slash characters and the matching part can be accessed as a path parameter value in the handlers.

If an incoming request matches multiple routes in the table, the route added first to the table will take precedence. All other matching routes will be ignored.

The actual implementation of the routing table uses a variant of the radix tree data structure, which makes the routing process as fast as working with a hash table, thanks to the inspiration from httprouter.

To add a new route and its handlers to the routing table, call the To method like the following:

r := tokay.New()
r.To("GET", "/users", m1, m2, h1)
r.To("POST", "/users", m1, m2, h2)

You can also use shortcut methods, such as Get, Post, Put, etc., which are named after the HTTP method names:

r.GET("/users", m1, m2, h1)
r.POST("/users", m1, m2, h2)

If you have multiple routes with the same URL path but different HTTP methods, like the above example, you can chain them together as follows,

r.GET("/users", m1, m2, h1).POST(m1, m2, h2)

If you want to use the same set of handlers to handle the same URL path but different HTTP methods, you can take the following shortcut:

r.To("GET,POST", "/users", m1, m2, h)

A route may contain parameter tokens which are in the format of <name:pattern>, where name stands for the parameter name, and pattern is a regular expression which the parameter value should match. A token <name> is equivalent to <name:[^/]*>, i.e., it matches any number of non-slash characters. At the end of a route, an asterisk character can be used to match any number of arbitrary characters. Below are some examples:

  • /users/<username>: matches /users/admin
  • /users/accnt-<id:\d+>: matches /users/accnt-123, but not /users/accnt-admin
  • /users/<username>/*: matches /users/admin/profile/address

When a URL path matches a route, the matching parameters on the URL path can be accessed via Context.Param():

r := tokay.New()

r.GET("/users/<username>", func (c *tokay.Context) {
	fmt.Fprintf(c, "Name: %v", c.Param("username"))
})

Route Groups

Route group is a way of grouping together the routes which have the same route prefix. The routes in a group also share the same handlers that are registered with the group via its Use method. For example,

r := tokay.New()
api := r.Group("/api")
api.Use(m1, m2)
api.GET("/users", h1).POST(h2)
api.PUT("/users/<id>", h3).DELETE(h4)

The above /api route group establishes the following routing table:

Routes Handlers
GET /api/users m1, m2, h1, ...
POST /api/users m1, m2, h2, ...
PUT /api/users/<id> m1, m2, h3, ...
DELETE /api/users/<id> m1, m2, h4, ...

As you can see, all these routes have the same route prefix /api and the handlers m1 and m2. In other similar routing frameworks, the handlers registered with a route group are also called middlewares.

Route groups can be nested. That is, a route group can create a child group by calling the Group() method. The router serves as the top level route group. A child group inherits the handlers registered with its parent group. For example,

r := tokay.New()
r.Use(m1)

api := r.Group("/api")
api.Use(m2)

users := api.Group("/users")
users.Use(m3)
users.PUT("/<id>", h1)

Because the router serves as the parent of the api group which is the parent of the users group, the PUT /api/users/<id> route is associated with the handlers m1, m2, m3, and h1.

Router

Router manages the routing table and dispatches incoming requests to appropriate handlers. A router instance is created by calling the tokay.New() method.

To hook up engine with fasthttp, use the following code:

r := tokay.New()
panic(r.Run(":8080"))

Handlers

A handler is a function with the signature func(*tokay.Context). A handler is executed by the router if the incoming request URL path matches the route that the handler is associated with. Through the tokay.Context parameter, you can access the request information in handlers.

A route may be associated with multiple handlers. These handlers will be executed in the order that they are registered to the route. The execution sequence can be terminated in the middle using one of the following method. A handler calls Context.Abort(): the router will simply skip the rest of the handlers.

A handler can call Context.Next() to explicitly execute the rest of the unexecuted handlers and take actions after they finish execution. For example, a response compression handler may start the output buffer, call Context.Next(), and then compress and send the output to response.

BasicAuth() middleware

BasicAuth method returns a Basic HTTP Authorization middleware. It takes even number of string arguments (username1, password1, username2, password2, etc...)

r := tokay.New()

// Group using tokay.BasicAuth() middleware
authorized := r.Group("/admin", tokay.BasicAuth("foo", "bar", "austin", "1234", "lena", "hello2"))

authorized.GET("/secrets", func(c *tokay.Context) {
    // get user, it was set by the BasicAuth middleware
    user := c.Get(tokay.AuthUserKey).(string)
    c.String(200, "Hello "+user+"!")
})

// Listen and serve on 0.0.0.0:8080
panic(r.Run(":8000"))

Context

For each incoming request, a tokay.Context object is passed through the relevant handlers. Because tokay.Context embeds fasthttp.RequestCtx, you can access all properties and methods provided by the latter.

Additionally, the Context.Param() method allows handlers to access the URL path parameters that match the current route. Using Context.Get() and Context.Set(), handlers can share data between each other. For example, an authentication handler can store the authenticated user identity by calling Context.Set(), and other handlers can retrieve back the identity information by calling Context.Get().

Context also provides a handy WriteData() method that can be used to write data of arbitrary type to the response. The WriteData() method can also be overridden (by replacement) to achieve more versatile response data writing.

Error Handling

When an incoming request has no matching route, the router will call the handlers registered via the Router.NotFound() method. All the handlers registered via Router.Use() will also be called in advance. By default, the following two handlers are registered with Router.NotFound():

  • tokay.MethodNotAllowedHandler: a handler that sends an Allow HTTP header indicating the allowed HTTP methods for a requested URL
  • tokay.NotFoundHandler: a handler triggering 404 HTTP error

Documentation

Index

Constants

View Source
const AuthUserKey = "basicAuthUuser"

AuthUserKey is the cookie name for user credential in basic auth.

Variables

View Source
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",
	}
)
View Source
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

func Env(envName string, defaultValue string) (value string)

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

func NewGracefulListener(ln net.Listener, maxWaitTime time.Duration) net.Listener

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.

func Serialize

func Serialize(data interface{}) (bytes []byte, err error)

Serialize converts the given data into a byte array. If the data is neither a byte array nor a string, it will call fmt.Sprint to convert it into a string.

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

func (c *Context) AbortWithError(statusCode int, err error)

AbortWithError calls `AbortWithStatus()` and `Error()` internally.

func (*Context) AbortWithStatus added in v1.0.1

func (c *Context) AbortWithStatus(statusCode int)

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

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

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

func (c *Context) BindJSON(obj interface{}) error

BindJSON binds the passed struct pointer with JSON request body data

func (*Context) BindPostForm added in v1.0.3

func (c *Context) BindPostForm(obj interface{}) error

BindPostForm binds the passed struct pointer with form data

func (*Context) BindQuery added in v1.0.3

func (c *Context) BindQuery(obj interface{}) error

BindQuery binds the passed struct pointer with Query data

func (*Context) BindXML added in v1.0.3

func (c *Context) BindXML(obj interface{}) error

BindXML binds the passed struct pointer with XML request body data

func (*Context) Body added in v1.0.1

func (c *Context) Body() []byte

Body returns request body The returned body is valid until the request modification.

func (*Context) ClientIP added in v1.0.1

func (c *Context) ClientIP() string

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

func (c *Context) ContentType() string

ContentType returns the Content-Type header of the request.

func (*Context) Cookie added in v1.0.1

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

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

func (c *Context) Copy() *Context

Copy context (instance will be contain copies of Request and Response)

func (*Context) Data added in v1.0.1

func (c *Context) Data(statusCode int, contentType string, data []byte)

Data writes some data into the body stream and updates the HTTP code.

func (*Context) Engine

func (c *Context) Engine() *Engine

Engine returns the Engine that is handling the incoming HTTP request.

func (*Context) Error added in v1.0.2

func (c *Context) Error(msg string, statusCode int)

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

func (c *Context) File(filepath string)

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

func (c *Context) Get(name string) (value interface{})

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

func (c *Context) GetEx(name string) (value interface{}, ok bool)

GetEx returns the named data item and info about data item exists.

func (*Context) GetHeader added in v1.0.1

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

GetHeader returns value from request headers.

func (*Context) HTML

func (c *Context) HTML(statusCode int, name string, obj interface{})

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

func (c *Context) Header(key, value string)

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) Host added in v1.0.2

func (c *Context) Host() string

Host returns Host header value.

func (*Context) IsAborted added in v1.0.1

func (c *Context) IsAborted() bool

IsAborted returns true if the current context was aborted.

func (*Context) JS added in v1.2.5

func (c *Context) JS(statusCode int, name string, obj interface{})

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

func (c *Context) JSON(statusCode int, obj interface{})

JSON serializes the given struct as JSON into the response body. It also sets the Content-Type as "application/json".

func (*Context) JSONP

func (c *Context) JSONP(statusCode int, callbackName string, obj interface{})

JSONP marshals the given interface object and writes the JSON response.

func (*Context) Method added in v1.0.2

func (c *Context) Method() string

Method returns request method.

func (*Context) MultipartForm added in v1.0.2

func (c *Context) MultipartForm() (*multipart.Form, error)

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

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

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

func (c *Context) ParamBool(name string) bool

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

func (c *Context) ParamFloat64(name string) float64

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

func (c *Context) ParamInt(name string) int

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

func (c *Context) ParamUint(name string) uint

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) Path added in v1.0.2

func (c *Context) Path() string

Path returns requested path.

func (*Context) PostForm added in v1.0.1

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

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

func (c *Context) PostFormArray(key string) []string

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

func (c *Context) PostFormArrayEx(key string) ([]string, bool)

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

func (c *Context) PostFormDefault(key, defaultValue string) string

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

func (c *Context) PostFormEx(key string) (string, bool)

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

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

Query returns the keyed url query value if it exists, otherwise it returns an empty string "".

func (*Context) QueryArray added in v1.0.1

func (c *Context) QueryArray(key string) []string

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

func (c *Context) QueryArrayEx(key string) ([]string, bool)

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

func (c *Context) QueryBool(name string) bool

QueryBool returns the boolean query value if it exists, otherwise it returns `false`

func (*Context) QueryDefault added in v1.0.2

func (c *Context) QueryDefault(key, defaultValue string) string

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

func (c *Context) QueryEx(key string) (string, bool)

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

func (c *Context) QueryFloat64(name string) float64

QueryFloat64 returns the float64 query value if it exists, otherwise it returns .0

func (*Context) QueryInt added in v1.2.1

func (c *Context) QueryInt(name string) int

QueryInt returns the integer query value if it exists, otherwise it returns 0

func (*Context) QueryUint added in v1.2.1

func (c *Context) QueryUint(name string) uint

QueryUint returns the uint query value if it exists, otherwise it returns 0

func (*Context) Redirect added in v1.0.1

func (c *Context) Redirect(statusCode int, uri string)

Redirect returns a HTTP redirect to the specific location.

func (*Context) Referer added in v1.0.2

func (c *Context) Referer() string

Referer returns request referer.

func (*Context) RemoveCookie added in v1.0.2

func (c *Context) RemoveCookie(name string)

RemoveCookie instructs the client to remove the given cookie.

func (*Context) RequestURI added in v1.0.2

func (c *Context) RequestURI() string

RequestURI returns RequestURI.

func (*Context) SaveFormFile added in v1.0.2

func (c *Context) SaveFormFile(name, path string) (err error)

SaveFormFile saves uploaded file associated with the given multipart form key under the given filename path.

func (*Context) Set

func (c *Context) Set(name string, value interface{})

Set stores the named data item in the context so that it can be retrieved later.

func (*Context) SetContentType added in v1.0.1

func (c *Context) SetContentType(contentType string)

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

func (c *Context) SetStatusCode(statusCode int)

SetStatusCode sets response status code.

func (*Context) String

func (c *Context) String(statusCode int, format string, values ...interface{})

String writes the given string into the response body.

func (*Context) URL

func (c *Context) URL(route string, pairs ...interface{}) string

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

func (c *Context) Unset(name string)

Unset the named data item in the context.

func (*Context) Websocket added in v1.0.5

func (c *Context) Websocket(fn func(), bufferSizes ...int) error

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

func (*Context) WriteData

func (c *Context) WriteData(data interface{}) (err error)

WriteData writes the given data of arbitrary type to the response. The method calls the Serialize() method to convert the data into a byte array and then writes the byte array to the response.

func (*Context) XML

func (c *Context) XML(statusCode int, obj interface{})

XML serializes the given struct as XML into the response body. It also sets the Content-Type as "application/xml".

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 New

func New(config ...*Config) *Engine

New creates a new Engine object.

func (*Engine) HandleRequest

func (engine *Engine) HandleRequest(ctx *fasthttp.RequestCtx)

HandleRequest handles the HTTP request.

func (*Engine) NotFound

func (engine *Engine) NotFound(handlers ...Handler)

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

func (engine *Engine) Route(name string) *Route

Route returns the named route. Nil is returned if the named route cannot be found.

func (*Engine) Run

func (engine *Engine) Run(addr string, message ...string) error

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

func (engine *Engine) RunTLS(addr string, certFile, keyFile string, message ...string) error

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

func (engine *Engine) RunUnix(addr string, mode os.FileMode, message ...string) error

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.

func (*Engine) Serve added in v1.4.6

func (engine *Engine) Serve(addr string, cfg *tls.Config, message ...string) error

Serve serves incoming connections from the given listener using the given handler. Serve blocks until the given listener returns permanent error.

func (*Engine) Use

func (engine *Engine) Use(handlers ...Handler)

Use appends the specified handlers to the engine and shares them with all routes.

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 Handler

type Handler func(*Context)

Handler is the function for handling HTTP requests.

func BasicAuth added in v1.0.1

func BasicAuth(accounts ...string) Handler

BasicAuth returns a Basic HTTP Authorization middleware. It takes even number of string arguments (username1, password1, username2, password2, etc...)

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

func (r *Route) CONNECT(handlers ...Handler) *Route

CONNECT adds the route to the engine using the CONNECT HTTP method.

func (*Route) DELETE

func (r *Route) DELETE(handlers ...Handler) *Route

DELETE adds the route to the engine using the DELETE HTTP method.

func (*Route) GET

func (r *Route) GET(handlers ...Handler) *Route

GET adds the route to the engine using the GET HTTP method.

func (*Route) HEAD

func (r *Route) HEAD(handlers ...Handler) *Route

HEAD adds the route to the engine using the HEAD HTTP method.

func (*Route) Name

func (r *Route) Name(name string) *Route

Name sets the name of the route. This method will update the registration of the route in the engine as well.

func (*Route) OPTIONS

func (r *Route) OPTIONS(handlers ...Handler) *Route

OPTIONS adds the route to the engine using the OPTIONS HTTP method.

func (*Route) PATCH

func (r *Route) PATCH(handlers ...Handler) *Route

PATCH adds the route to the engine using the PATCH HTTP method.

func (*Route) POST

func (r *Route) POST(handlers ...Handler) *Route

POST adds the route to the engine using the POST HTTP method.

func (*Route) PUT

func (r *Route) PUT(handlers ...Handler) *Route

PUT adds the route to the engine using the PUT HTTP method.

func (*Route) TRACE

func (r *Route) TRACE(handlers ...Handler) *Route

TRACE adds the route to the engine using the TRACE HTTP method.

func (*Route) To

func (r *Route) To(methods string, handlers ...Handler) *Route

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

func (r *Route) URL(pairs ...interface{}) (s string)

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

type SerializeFunc func(data interface{}) ([]byte, error)

SerializeFunc serializes the given data of arbitrary type into a byte array.

Jump to

Keyboard shortcuts

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