1
0
mirror of https://github.com/gofiber/fiber.git synced 2025-02-19 14:07:53 +00:00
fiber/router.go

496 lines
13 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/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 ...any) 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
Route(path string) Register
Mount(prefix string, fiber *App) Router
Name(name string) 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
Name string `json:"name"` // Route's name
2020-07-02 20:26:38 +02:00
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
}
func (app *App) next(c CustomCtx, customCtx bool) (match bool, err error) {
// Get stack length
tree, ok := app.treeStack[c.getMethodINT()][c.getTreePath()]
if !ok {
tree = app.treeStack[c.getMethodINT()][""]
}
lenr := len(tree) - 1
2020-09-13 11:20:11 +02:00
// Loop over the route stack starting from previous index
for c.getIndexRoute() < lenr {
// Increment route index
c.setIndexRoute(c.getIndexRoute() + 1)
2020-09-13 11:20:11 +02:00
// Get *Route
route := tree[c.getIndexRoute()]
2020-09-13 11:20:11 +02:00
// Check if it matches the request path
match = route.match(c.getDetectionPath(), c.Path(), c.getValues())
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
c.setRoute(route)
2020-09-13 11:20:11 +02:00
// Non use handler matched
if !c.getMatched() && !route.use {
c.setMatched(true)
}
// Execute first handler of route
c.setIndexHandler(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
err = NewError(StatusNotFound, "Cannot "+c.Method()+" "+c.getPathOriginal())
2020-09-13 11:20:11 +02:00
var isMethodExist bool
if customCtx {
isMethodExist = methodExistCustom(c)
} else {
isMethodExist = methodExist(c.(*DefaultCtx))
}
2020-09-13 11:20:11 +02:00
// 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.getMatched() && isMethodExist {
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) {
var c CustomCtx
if app.newCtxFunc != nil {
c = app.AcquireCtx().(CustomCtx)
} else {
c = app.AcquireCtx().(*DefaultCtx)
}
c.Reset(rctx)
2020-07-24 22:55:57 +08:00
// handle invalid http method directly
if methodInt(c.Method()) == -1 {
2020-09-13 11:20:11 +02:00
_ = 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
// check flash messages
if strings.Contains(utils.UnsafeString(c.Request().Header.RawHeaders()), FlashCookieName) {
c.Redirect().setFlash()
}
2020-05-16 05:14:01 +02:00
// Find match in stack
_, err := app.next(c, app.newCtxFunc != nil)
if err != nil {
if catch := c.App().ErrorHandler(c, err); catch != nil {
_ = c.SendStatus(StatusInternalServerError)
}
}
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 = strings.TrimRight(prettyPath, "/")
2020-09-13 11:20:11 +02:00
}
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 = strings.TrimRight(pathPretty, "/")
2020-03-24 12:20:07 +01:00
}
2020-05-16 05:14:01 +02:00
// Is layer a middleware?
isUse := method == methodUse
2020-05-16 05:14:01 +02:00
// Is path a direct wildcard?
isStar := pathPretty == "/*"
2020-05-16 05:14:01 +02:00
// Is path a root slash?
isRoot := pathPretty == "/"
2020-05-16 05:14:01 +02:00
// Parse path parameters
parsedRaw := parseRoute(pathRaw)
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.handlersCount, 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?
isStar := prefix == "/*"
// Is prefix a root slash?
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)
if prefixLen > 1 && prefix[prefixLen-1:] == "/" {
// /john/ -> /john
prefixLen--
prefix = prefix[:prefixLen]
}
2020-03-24 12:20:07 +01:00
// Fileserver settings
fs := &fasthttp.FS{
Root: root,
AllowEmptyRoot: true,
2020-03-24 12:20:07 +01:00
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 {
path = path[prefixLen:]
if len(path) == 0 || path[len(path)-1] != '/' {
path = append(path, '/')
}
}
}
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()
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
fileHandler(c.Context())
// Sets the response Content-Disposition header to attachment if the Download option is true
if len(config) > 0 && config[0].Download {
c.Attachment()
}
// Return request if found and not forbidden
status := c.Context().Response.StatusCode()
if status != StatusNotFound && status != StatusForbidden {
if len(cacheControlValue) > 0 {
c.Context().Response.Header.Set(HeaderCacheControl, cacheControlValue)
}
2020-09-13 11:20:11 +02:00
return nil
}
// Reset response to default
c.Context().SetContentType("") // Issue #420
c.Context().Response.SetStatusCode(StatusOK)
c.Context().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.handlersCount, 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
}
app.mutex.Lock()
app.latestRoute = route
if err := app.hooks.executeOnRouteHooks(*route); err != nil {
panic(err)
}
app.mutex.Unlock()
}
// 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 {
tsMap := 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
tsMap[treePath] = append(tsMap[treePath], route)
}
app.treeStack[m] = tsMap
}
// loop the methods and tree stacks and add global stack and sort everything
for m := range intMethod {
tsMap := app.treeStack[m]
for treePart := range tsMap {
if treePart != "" {
// merge global tree routes in current tree stack
tsMap[treePart] = uniqueRouteStack(append(tsMap[treePart], tsMap[""]...))
}
// sort tree slices with the positions
slc := tsMap[treePart]
sort.Slice(slc, func(i, j int) bool { return slc[i].pos < slc[j].pos })
}
}
app.routesRefreshed = false
return app
}