summaryrefslogtreecommitdiffci
path: root/internal/router/path-matcher.go
blob: c8aef0821c55ceeccbd21fef4c01453dda54d6f4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package router

import (
	"github.com/gofiber/fiber/v2"
	"github.com/valyala/fasthttp"
)

type PathMatcher struct {
	app *fiber.App
}

func NewPathMatcher() *PathMatcher {
	app := fiber.New(fiber.Config{
		DisableStartupMessage: true,
	})
	return &PathMatcher{app: app}
}

func (pm *PathMatcher) AddRoute(method, pattern string) {
	pm.app.Add(method, pattern, func(c *fiber.Ctx) error {
		c.Locals("pattern", pattern)
		return nil
	})
}

func (pm *PathMatcher) MatchPath(method, path string) (pattern string, params map[string]string, matched bool) {
	fctx := &fasthttp.RequestCtx{}
	fctx.Request.Header.SetMethod(method)
	fctx.Request.SetRequestURI(path)

	ctx := pm.app.AcquireCtx(fctx)
	defer pm.app.ReleaseCtx(ctx)

	pm.app.Handler()(fctx)

	if ctx.Route() == nil {
		return "", nil, false
	}

	pattern = ctx.Locals("pattern").(string)

	params = make(map[string]string)
	for _, paramName := range ctx.Route().Params {
		params[paramName] = ctx.Params(paramName)
	}

	return pattern, params, true
}