-
Notifications
You must be signed in to change notification settings - Fork 0
/
parameter_bag.go
64 lines (51 loc) · 1.53 KB
/
parameter_bag.go
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
package routing
import (
"fmt"
)
type urlParameter struct {
name string
value string
}
// URLParameterBag is a structure where the URL parameters are saved
type URLParameterBag struct {
params []urlParameter
capacity uint
}
func (u *URLParameterBag) add(name, value string) {
if u.params == nil {
u.params = make([]urlParameter, 0, u.capacity)
}
u.params = append(u.params, urlParameter{name, value})
}
// GetByName is a method to retrieve a dynamic parameter of the URL using a name. For example 'userId' in /users/{userId}
func (u *URLParameterBag) GetByName(name string) (string, error) {
for i := range u.params {
if u.params[i].name == name {
return u.params[i].value, nil
}
}
return "", fmt.Errorf("url parameter with name %s does not exist", name)
}
// GetByIndex is a method to retrieve a dynamic parameter of the URL using a index. For example 1 to obtain the 'userId' in /users/{userId}/file/{fileId}
func (u *URLParameterBag) GetByIndex(index uint) (string, error) {
i := int(index)
if len(u.params) <= i {
return "", fmt.Errorf("url parameter at index %d does not exist", i)
}
return u.params[i].value, nil
}
func (u URLParameterBag) merge(other URLParameterBag) URLParameterBag {
bag := newURLParameterBag(u.capacity + other.capacity)
for _, param := range u.params {
bag.add(param.name, param.value)
}
for _, param := range other.params {
bag.add(param.name, param.value)
}
return bag
}
func newURLParameterBag(capacity uint) URLParameterBag {
return URLParameterBag{
capacity: capacity,
}
}