Help us shape the future of Go! Take the 2026 Go Developer Survey

tokay

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2017 License: BSD-3-Clause Imports: 12 Imported by: 8

README

Tokay

GoDoc Go Report

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 Express 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.8 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() {
	router := tokay.New()
	
	router.GET("/", func(c *tokay.Context) {
		c.String(200, "Hello, world!")
	})
	
	panic(router.Run(":8080"))
}

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:

router := tokay.New()
router.To("GET", "/users", m1, m2, h1)
router.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:

router.GET("/users", m1, m2, h1)
router.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,

router.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:

router.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():

router := tokay.New()

router.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,

router := tokay.New()
api := router.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,

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

api := router.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 router with fasthttp, use the following code:

router := tokay.New()
panic(router.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.

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

This section is empty.

Variables

View Source
var Methods = []string{
	"CONNECT",
	"DELETE",
	"GET",
	"HEAD",
	"OPTIONS",
	"PATCH",
	"POST",
	"PUT",
	"TRACE",
}

Methods lists all supported HTTP methods by Engine.

Functions

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 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 Context

type Context struct {
	*fasthttp.RequestCtx
	Serialize SerializeFunc // the function serializing the given data of arbitrary type into a byte array.
	// 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) Engine

func (c *Context) Engine() *Engine

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

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

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

func (*Context) JSON

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

func (*Context) JSONP

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

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

func (c *Context) String(status int, text string)

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) 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(status int, obj interface{})

type Engine

type Engine struct {
	RouterGroup
	Render *render.Render
	// contains filtered or unexported fields
}

Engine manages routes and dispatches HTTP requests to the handlers of the matching routes.

func New

func New() *Engine

New creates a new Engine object.

func (*Engine) HandleRequest

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

HandleRequest handles the HTTP request.

func (*Engine) NotFound

func (r *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 (r *Engine) Route(name string) *Route

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

func (*Engine) Run

func (r *Engine) Run(addr string) (err error)

Run attaches the engine to a fasthttp server and starts listening and serving HTTP requests. It is a shortcut for fasthttp.ListenAndServe(addr, engine.HandleRequest) Note: this method will block the calling goroutine indefinitely unless an error happens.

func (*Engine) RunTLS

func (r *Engine) RunTLS(addr string, certFile, keyFile string) (err error)

RunTLS attaches the engine to a fasthttp server and starts listening and serving HTTPS (secure) requests. It is a shortcut for fasthttp.ListenAndServeTLS(addr, certFile, keyFile, engine.HandleRequest) Note: this method will block the calling goroutine indefinitely unless an error happens.

func (*Engine) RunUnix

func (r *Engine) RunUnix(addr string, mode os.FileMode) (err 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) Use

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

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

type Handler

type Handler func(*Context)

Handler is the function for handling HTTP requests.

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