1
0
mirror of https://github.com/gofiber/fiber.git synced 2025-02-19 13:47:54 +00:00
fiber/router.go

456 lines
12 KiB
Go
Raw Normal View History

// ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
// 🤖 Github Repository: https://github.com/gofiber/fiber
// 📌 API Documentation: https://docs.gofiber.io
2020-02-21 18:06:08 +01:00
2019-12-30 07:29:42 -05:00
package fiber
import (
2020-07-15 17:43:30 +02:00
"fmt"
"sort"
"strconv"
2020-03-24 12:20:07 +01:00
"strings"
"sync/atomic"
2020-03-24 12:20:07 +01:00
"time"
2019-12-30 07:29:42 -05:00
"github.com/gofiber/fiber/v2/utils"
2020-09-13 11:20:11 +02:00
"github.com/valyala/fasthttp"
2019-12-30 07:29:42 -05:00
)
// Router defines all router handle interface includes app and group router.
type Router interface {
Use(args ...interface{}) Router
Get(path string, handlers ...Handler) Router
Head(path string, handlers ...Handler) Router
Post(path string, handlers ...Handler) Router
Put(path string, handlers ...Handler) Router
Delete(path string, handlers ...Handler) Router
Connect(path string, handlers ...Handler) Router
Options(path string, handlers ...Handler) Router
Trace(path string, handlers ...Handler) Router
Patch(path string, handlers ...Handler) Router
Add(method, path string, handlers ...Handler) Router
Static(prefix, root string, config ...Static) Router
All(path string, handlers ...Handler) Router
Group(prefix string, handlers ...Handler) Router
Mount(prefix string, fiber *App) Router
}
// Route is a struct that holds all metadata for each registered handler
type Route struct {
// Data for routing
pos uint32 // Position in stack -> important for the sort of the matched routes
2020-06-20 17:27:40 +02:00
use bool // USE matches path prefixes
star bool // Path equals '*'
root bool // Path equals '/'
path string // Prettified path
routeParser routeParser // Parameter parser
// Public fields
2020-07-02 20:26:38 +02:00
Method string `json:"method"` // HTTP method
Path string `json:"path"` // Original registered route path
2020-07-05 11:17:42 +02:00
Params []string `json:"params"` // Case sensitive param keys
2020-07-02 20:26:38 +02:00
Handlers []Handler `json:"-"` // Ctx handlers
}
func (r *Route) match(detectionPath, path string, params *[maxParams]string) (match bool) {
// root detectionPath check
if r.root && detectionPath == "/" {
2020-09-13 11:20:11 +02:00
return true
// '*' wildcard matches any detectionPath
2020-05-24 14:47:32 +02:00
} else if r.star {
if len(path) > 1 {
params[0] = path[1:]
2020-10-21 14:50:18 +08:00
} else {
params[0] = ""
2020-09-02 20:59:42 +02:00
}
2020-09-13 11:20:11 +02:00
return true
2020-05-24 14:47:32 +02:00
}
2020-05-24 14:01:52 +02:00
// Does this route have parameters
2020-07-05 11:17:42 +02:00
if len(r.Params) > 0 {
2020-05-24 14:01:52 +02:00
// Match params
if match := r.routeParser.getMatch(detectionPath, path, params, r.use); match {
// Get params from the path detectionPath
2020-09-13 11:20:11 +02:00
return match
2020-05-24 14:01:52 +02:00
}
}
// Is this route a Middleware?
if r.use {
// Single slash will match or detectionPath prefix
if r.root || strings.HasPrefix(detectionPath, r.path) {
2020-09-13 11:20:11 +02:00
return true
}
// Check for a simple detectionPath match
} else if len(r.path) == len(detectionPath) && r.path == detectionPath {
2020-09-13 11:20:11 +02:00
return true
}
// No match
2020-09-13 11:20:11 +02:00
return false
}
2020-09-13 11:20:11 +02:00
func (app *App) next(c *Ctx) (match bool, err error) {
// Get stack length
2020-09-13 11:20:11 +02:00
tree, ok := app.treeStack[c.methodINT][c.treePath]
if !ok {
2020-09-13 11:20:11 +02:00
tree = app.treeStack[c.methodINT][""]
}
lenr := len(tree) - 1
2020-09-13 11:20:11 +02:00
// Loop over the route stack starting from previous index
2020-09-13 11:20:11 +02:00
for c.indexRoute < lenr {
// Increment route index
2020-09-13 11:20:11 +02:00
c.indexRoute++
// Get *Route
2020-09-13 11:20:11 +02:00
route := tree[c.indexRoute]
// Check if it matches the request path
match = route.match(c.detectionPath, c.path, &c.values)
2020-09-13 11:20:11 +02:00
// No match, next route
if !match {
continue
2020-03-24 12:20:07 +01:00
}
// Pass route reference and param values
2020-09-13 11:20:11 +02:00
c.route = route
// Non use handler matched
2020-09-13 11:20:11 +02:00
if !c.matched && !route.use {
c.matched = true
}
// Execute first handler of route
2020-09-13 11:20:11 +02:00
c.indexHandler = 0
err = route.Handlers[0](c)
return match, err // Stop scanning the stack
2020-03-24 12:20:07 +01:00
}
2020-09-13 11:20:11 +02:00
2020-06-01 13:45:04 +02:00
// If c.Next() does not match, return 404
2020-09-13 11:20:11 +02:00
_ = c.SendStatus(StatusNotFound)
_ = c.SendString("Cannot " + c.method + " " + c.pathOriginal)
// If no match, scan stack again if other methods match the request
// Moved from app.handler because middleware may break the route chain
if !c.matched && methodExist(c) {
err = ErrMethodNotAllowed
}
2020-09-13 11:20:11 +02:00
return
2020-03-04 12:30:29 +01:00
}
2020-05-16 05:14:01 +02:00
func (app *App) handler(rctx *fasthttp.RequestCtx) {
// Acquire Ctx with fasthttp request from pool
2020-09-13 11:20:11 +02:00
c := app.AcquireCtx(rctx)
2020-07-24 22:55:57 +08:00
// handle invalid http method directly
2020-09-13 11:20:11 +02:00
if c.methodINT == -1 {
_ = c.Status(StatusBadRequest).SendString("Invalid http method")
app.ReleaseCtx(c)
2020-07-24 22:55:57 +08:00
return
}
2020-09-13 11:20:11 +02:00
2020-05-16 05:14:01 +02:00
// Find match in stack
match, err := app.next(c)
if err != nil {
if catch := c.app.config.ErrorHandler(c, err); catch != nil {
_ = c.SendStatus(StatusInternalServerError)
}
}
2020-06-01 13:45:04 +02:00
// Generate ETag if enabled
2020-09-13 11:20:11 +02:00
if match && app.config.ETag {
setETag(c, false)
2020-03-24 12:20:07 +01:00
}
2020-05-16 05:14:01 +02:00
// Release Ctx
2020-09-13 11:20:11 +02:00
app.ReleaseCtx(c)
2020-02-27 04:10:26 -05:00
}
2020-03-03 12:21:34 -05:00
2020-09-13 11:20:11 +02:00
func (app *App) addPrefixToRoute(prefix string, route *Route) *Route {
prefixedPath := getGroupPath(prefix, route.Path)
prettyPath := prefixedPath
// Case sensitive routing, all to lowercase
if !app.config.CaseSensitive {
prettyPath = utils.ToLower(prettyPath)
}
// Strict routing, remove trailing slashes
if !app.config.StrictRouting && len(prettyPath) > 1 {
prettyPath = utils.TrimRight(prettyPath, '/')
}
route.Path = prefixedPath
route.path = RemoveEscapeChar(prettyPath)
2020-09-13 11:20:11 +02:00
route.routeParser = parseRoute(prettyPath)
route.root = false
route.star = false
return route
}
func (app *App) copyRoute(route *Route) *Route {
return &Route{
// Router booleans
use: route.use,
star: route.star,
root: route.root,
// Path data
path: route.path,
routeParser: route.routeParser,
Params: route.Params,
// Public data
2021-08-04 22:32:05 -07:00
Path: route.Path,
2020-09-13 11:20:11 +02:00
Method: route.Method,
Handlers: route.Handlers,
}
}
func (app *App) register(method, pathRaw string, handlers ...Handler) Router {
// Uppercase HTTP methods
method = utils.ToUpper(method)
// Check if the HTTP method is valid unless it's USE
if method != methodUse && methodInt(method) == -1 {
2020-07-15 17:43:30 +02:00
panic(fmt.Sprintf("add: invalid http method %s\n", method))
}
// A route requires atleast one ctx handler
2020-03-24 12:20:07 +01:00
if len(handlers) == 0 {
2020-07-15 17:43:30 +02:00
panic(fmt.Sprintf("missing handler in route: %s\n", pathRaw))
2020-03-24 12:20:07 +01:00
}
// Cannot have an empty path
if pathRaw == "" {
pathRaw = "/"
2020-03-24 12:20:07 +01:00
}
2020-05-16 05:14:01 +02:00
// Path always start with a '/'
if pathRaw[0] != '/' {
pathRaw = "/" + pathRaw
2020-03-24 12:20:07 +01:00
}
// Create a stripped path in-case sensitive / trailing slashes
pathPretty := pathRaw
2020-03-24 12:20:07 +01:00
// Case sensitive routing, all to lowercase
2020-09-13 11:20:11 +02:00
if !app.config.CaseSensitive {
pathPretty = utils.ToLower(pathPretty)
2020-03-24 12:20:07 +01:00
}
// Strict routing, remove trailing slashes
2020-09-13 11:20:11 +02:00
if !app.config.StrictRouting && len(pathPretty) > 1 {
pathPretty = utils.TrimRight(pathPretty, '/')
2020-03-24 12:20:07 +01:00
}
2020-05-16 05:14:01 +02:00
// Is layer a middleware?
var isUse = method == methodUse
2020-05-16 05:14:01 +02:00
// Is path a direct wildcard?
var isStar = pathPretty == "/*"
2020-05-16 05:14:01 +02:00
// Is path a root slash?
var isRoot = pathPretty == "/"
2020-05-16 05:14:01 +02:00
// Parse path parameters
var parsedRaw = parseRoute(pathRaw)
var parsedPretty = parseRoute(pathPretty)
2020-07-20 19:29:54 +02:00
// Create route metadata without pointer
route := Route{
// Router booleans
use: isUse,
star: isStar,
root: isRoot,
2020-09-13 11:20:11 +02:00
// Path data
path: RemoveEscapeChar(pathPretty),
routeParser: parsedPretty,
2020-07-05 11:17:42 +02:00
Params: parsedRaw.params,
// Public data
Path: pathRaw,
Method: method,
Handlers: handlers,
}
// Increment global handler count
atomic.AddUint32(&app.handlerCount, uint32(len(handlers)))
2020-09-13 11:20:11 +02:00
2020-07-20 19:29:54 +02:00
// Middleware route matches all HTTP methods
if isUse {
// Add route to all HTTP methods stack
for _, m := range intMethod {
2020-09-13 11:20:11 +02:00
// Create a route copy to avoid duplicates during compression
2020-07-20 19:29:54 +02:00
r := route
app.addRoute(m, &r)
}
2020-09-13 11:20:11 +02:00
} else {
// Add route to stack
app.addRoute(method, &route)
2020-07-20 19:29:54 +02:00
}
2020-09-13 11:20:11 +02:00
return app
2019-12-30 13:33:50 +01:00
}
2020-03-03 12:21:34 -05:00
2020-09-13 11:20:11 +02:00
func (app *App) registerStatic(prefix, root string, config ...Static) Router {
// For security we want to restrict to the current work directory.
if root == "" {
root = "."
}
2020-03-24 12:20:07 +01:00
// Cannot have an empty prefix
if prefix == "" {
prefix = "/"
}
// Prefix always start with a '/' or '*'
if prefix[0] != '/' {
2020-03-24 12:20:07 +01:00
prefix = "/" + prefix
}
2020-05-16 05:14:01 +02:00
// in case sensitive routing, all to lowercase
2020-09-13 11:20:11 +02:00
if !app.config.CaseSensitive {
prefix = utils.ToLower(prefix)
2020-03-24 12:20:07 +01:00
}
// Strip trailing slashes from the root path
if len(root) > 0 && root[len(root)-1] == '/' {
root = root[:len(root)-1]
}
// Is prefix a direct wildcard?
var isStar = prefix == "/*"
// Is prefix a root slash?
var isRoot = prefix == "/"
// Is prefix a partial wildcard?
2020-03-24 12:20:07 +01:00
if strings.Contains(prefix, "*") {
// /john* -> /john
isStar = true
2020-03-24 12:20:07 +01:00
prefix = strings.Split(prefix, "*")[0]
// Fix this later
2020-03-24 12:20:07 +01:00
}
prefixLen := len(prefix)
2020-03-24 12:20:07 +01:00
// Fileserver settings
fs := &fasthttp.FS{
Root: root,
GenerateIndexPages: false,
AcceptByteRange: false,
Compress: false,
2020-09-13 11:20:11 +02:00
CompressedFileSuffix: app.config.CompressedFileSuffix,
2020-03-24 12:20:07 +01:00
CacheDuration: 10 * time.Second,
IndexNames: []string{"index.html"},
2020-09-13 11:20:11 +02:00
PathRewrite: func(fctx *fasthttp.RequestCtx) []byte {
path := fctx.Path()
if len(path) >= prefixLen {
if isStar && app.getString(path[0:prefixLen]) == prefix {
2020-06-03 21:35:49 +02:00
path = append(path[0:0], '/')
} else if len(path) > 0 && path[len(path)-1] != '/' {
2020-06-03 21:35:49 +02:00
path = append(path[prefixLen:], '/')
}
}
2020-06-03 21:35:49 +02:00
if len(path) > 0 && path[0] != '/' {
path = append([]byte("/"), path...)
}
2020-06-03 17:16:10 +02:00
return path
},
2020-09-13 11:20:11 +02:00
PathNotFound: func(fctx *fasthttp.RequestCtx) {
fctx.Response.SetStatusCode(StatusNotFound)
2020-03-24 12:20:07 +01:00
},
}
2020-03-24 12:20:07 +01:00
// Set config if provided
var cacheControlValue string
2020-03-24 12:20:07 +01:00
if len(config) > 0 {
maxAge := config[0].MaxAge
if maxAge > 0 {
cacheControlValue = "public, max-age=" + strconv.Itoa(maxAge)
}
fs.CacheDuration = config[0].CacheDuration
2020-03-24 12:20:07 +01:00
fs.Compress = config[0].Compress
fs.AcceptByteRange = config[0].ByteRange
fs.GenerateIndexPages = config[0].Browse
if config[0].Index != "" {
fs.IndexNames = []string{config[0].Index}
}
}
fileHandler := fs.NewRequestHandler()
2020-09-13 11:20:11 +02:00
handler := func(c *Ctx) error {
// Don't execute middleware if Next returns true
if len(config) != 0 && config[0].Next != nil && config[0].Next(c) {
return c.Next()
}
// Serve file
2020-09-13 11:20:11 +02:00
fileHandler(c.fasthttp)
// Return request if found and not forbidden
2020-09-13 11:20:11 +02:00
status := c.fasthttp.Response.StatusCode()
if status != StatusNotFound && status != StatusForbidden {
if len(cacheControlValue) > 0 {
c.fasthttp.Response.Header.Set(HeaderCacheControl, cacheControlValue)
}
2020-09-13 11:20:11 +02:00
return nil
}
// Reset response to default
2020-09-13 11:20:11 +02:00
c.fasthttp.SetContentType("") // Issue #420
c.fasthttp.Response.SetStatusCode(StatusOK)
c.fasthttp.Response.SetBodyString("")
// Next middleware
2020-09-13 11:20:11 +02:00
return c.Next()
}
2020-07-20 19:29:54 +02:00
// Create route metadata without pointer
route := Route{
// Router booleans
use: true,
root: isRoot,
path: prefix,
// Public data
Method: MethodGet,
Path: prefix,
Handlers: []Handler{handler},
}
// Increment global handler count
atomic.AddUint32(&app.handlerCount, 1)
// Add route to stack
2020-07-20 19:29:54 +02:00
app.addRoute(MethodGet, &route)
// Add HEAD route
2020-09-13 11:20:11 +02:00
app.addRoute(MethodHead, &route)
return app
}
2020-06-20 17:26:48 +02:00
2020-07-20 19:29:54 +02:00
func (app *App) addRoute(method string, route *Route) {
// Get unique HTTP method identifier
2020-07-20 19:29:54 +02:00
m := methodInt(method)
2020-07-20 19:29:54 +02:00
// prevent identically route registration
l := len(app.stack[m])
if l > 0 && app.stack[m][l-1].Path == route.Path && route.use == app.stack[m][l-1].use {
preRoute := app.stack[m][l-1]
2020-07-20 19:29:54 +02:00
preRoute.Handlers = append(preRoute.Handlers, route.Handlers...)
} else {
// Increment global route position
route.pos = atomic.AddUint32(&app.routesCount, 1)
route.Method = method
2020-07-20 19:29:54 +02:00
// Add route to the stack
app.stack[m] = append(app.stack[m], route)
app.routesRefreshed = true
}
}
// buildTree build the prefix tree from the previously registered routes
func (app *App) buildTree() *App {
2021-01-26 21:57:58 +03:00
if !app.routesRefreshed {
return app
}
// loop all the methods and stacks and create the prefix tree
for m := range intMethod {
app.treeStack[m] = make(map[string][]*Route)
for _, route := range app.stack[m] {
treePath := ""
if len(route.routeParser.segs) > 0 && len(route.routeParser.segs[0].Const) >= 3 {
treePath = route.routeParser.segs[0].Const[:3]
}
// create tree stack
app.treeStack[m][treePath] = append(app.treeStack[m][treePath], route)
}
}
// loop the methods and tree stacks and add global stack and sort everything
for m := range intMethod {
for treePart := range app.treeStack[m] {
if treePart != "" {
// merge global tree routes in current tree stack
app.treeStack[m][treePart] = uniqueRouteStack(append(app.treeStack[m][treePart], app.treeStack[m][""]...))
}
// sort tree slices with the positions
sort.Slice(app.treeStack[m][treePart], func(i, j int) bool {
return app.treeStack[m][treePart][i].pos < app.treeStack[m][treePart][j].pos
})
}
}
app.routesRefreshed = false
return app
}