-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnamed_routes.go
More file actions
183 lines (161 loc) · 4.08 KB
/
named_routes.go
File metadata and controls
183 lines (161 loc) · 4.08 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package nanite
import (
"fmt"
"net/url"
"strings"
)
type segmentKind uint8
const (
segmentStatic segmentKind = iota
segmentParam
segmentWildcard
)
type routeSegment struct {
kind segmentKind
value string
}
type namedRoute struct {
method string
path string
segments []routeSegment
}
// URL resolves a named route into a concrete path.
// params keys should match route placeholders (":id" => "id", "*path" => "path").
func (r *Router) URL(name string, params map[string]string) (string, error) {
r.mutex.RLock()
route, ok := r.namedRoutes[name]
r.mutex.RUnlock()
if !ok {
return "", fmt.Errorf("named route %q not found", name)
}
if len(route.segments) == 0 {
return "/", nil
}
var b strings.Builder
b.WriteByte('/')
for i, seg := range route.segments {
if i > 0 {
b.WriteByte('/')
}
switch seg.kind {
case segmentStatic:
b.WriteString(seg.value)
case segmentParam, segmentWildcard:
v := ""
if params != nil {
v = params[seg.value]
}
if v == "" {
return "", fmt.Errorf("missing parameter %q for route %q", seg.value, name)
}
b.WriteString(v)
}
}
return b.String(), nil
}
// MustURL resolves a named route and panics on error.
func (r *Router) MustURL(name string, params map[string]string) string {
url, err := r.URL(name, params)
if err != nil {
panic(err)
}
return url
}
// URLWithQuery resolves a named route and appends encoded query parameters.
func (r *Router) URLWithQuery(name string, params map[string]string, query map[string]string) (string, error) {
base, err := r.URL(name, params)
if err != nil {
return "", err
}
if len(query) == 0 {
return base, nil
}
values := url.Values{}
for key, value := range query {
values.Set(key, value)
}
encoded := values.Encode()
if encoded == "" {
return base, nil
}
return base + "?" + encoded, nil
}
// MustURLWithQuery resolves a named route with query params and panics on error.
func (r *Router) MustURLWithQuery(name string, params map[string]string, query map[string]string) string {
u, err := r.URLWithQuery(name, params, query)
if err != nil {
panic(err)
}
return u
}
// NamedRoute returns metadata for a registered named route.
func (r *Router) NamedRoute(name string) (method, path string, ok bool) {
r.mutex.RLock()
route, exists := r.namedRoutes[name]
r.mutex.RUnlock()
if !exists {
return "", "", false
}
return route.method, route.path, true
}
func (r *Router) registerNamedRoute(name, method, path string) error {
if name == "" {
return fmt.Errorf("route name cannot be empty")
}
normalizedPath, segments, err := parseRouteTemplate(path)
if err != nil {
return err
}
r.mutex.Lock()
defer r.mutex.Unlock()
if _, exists := r.namedRoutes[name]; exists {
return fmt.Errorf("named route %q already registered", name)
}
r.namedRoutes[name] = namedRoute{
method: method,
path: normalizedPath,
segments: segments,
}
return nil
}
func parseRouteTemplate(path string) (string, []routeSegment, error) {
if path == "" {
path = "/"
}
if path[0] != '/' {
path = "/" + path
}
if len(path) > 1 && path[len(path)-1] == '/' {
path = strings.TrimSuffix(path, "/")
}
if path == "/" {
return path, nil, nil
}
parts := strings.Split(path[1:], "/")
segments := make([]routeSegment, 0, len(parts))
for i, part := range parts {
if part == "" {
return "", nil, fmt.Errorf("invalid route template %q: empty path segment", path)
}
switch part[0] {
case ':':
name := part[1:]
if name == "" {
return "", nil, fmt.Errorf("invalid route template %q: empty param name", path)
}
segments = append(segments, routeSegment{kind: segmentParam, value: name})
case '*':
name := part[1:]
if name == "" {
return "", nil, fmt.Errorf("invalid route template %q: empty wildcard name", path)
}
if i != len(parts)-1 {
return "", nil, fmt.Errorf("invalid route template %q: wildcard must be final segment", path)
}
segments = append(segments, routeSegment{kind: segmentWildcard, value: name})
default:
segments = append(segments, routeSegment{kind: segmentStatic, value: part})
}
}
return path, segments, nil
}