aboutsummaryrefslogtreecommitdiff
path: root/utils/urls/path.go
blob: a3b3ec997827cd2f6f312ce5f8076dd344104bfa (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package urls

import (
	"strings"

	"github.com/gofiber/fiber/v2"
)

type HTTPMethod string

const (
	Delete  HTTPMethod = "DELETE"
	Get     HTTPMethod = "GET"
	Head    HTTPMethod = "HEAD"
	Options HTTPMethod = "OPTIONS"
	Patch   HTTPMethod = "PATCH"
	Post    HTTPMethod = "POST"
	Put     HTTPMethod = "PUT"
)

func Path(method HTTPMethod, path string, handler fiber.Handler, name string) {
	registry.Mutex.Lock()
	defer registry.Mutex.Unlock()

	namespace := registry.CurrentNamespace
	fullName := resolveFullName(namespace, name)
	fullPath := resolveFullPath(namespace, path)

	registry.Routes[fullName] = RegisteredRoute{
		Method:    method,
		Path:      path,
		Handler:   handler,
		Namespace: namespace,
		Name:      name,
		FullPath:  fullPath,
	}
}

func GetFullPath(routeName string) (string, bool) {
	registry.Mutex.Lock()
	defer registry.Mutex.Unlock()

	route, exists := registry.Routes[routeName]
	if !exists {
		return "", false
	}

	return route.FullPath, true
}

func resolveFullName(namespace string, name string) string {
	switch namespace {
	case "":
		return name
	default:
		return namespace + "." + name
	}
}

func resolveFullPath(namespace string, path string) string {
	switch namespace {
	case "":
		return ensureLeadingSlash(path)
	default:
		return "/" + namespace + ensureLeadingSlash(path)
	}
}

func ensureLeadingSlash(path string) string {
	switch strings.HasPrefix(path, "/") {
	case true:
		return path
	default:
		return "/" + path
	}
}