-
Notifications
You must be signed in to change notification settings - Fork 2
/
router.go
69 lines (56 loc) · 1.67 KB
/
router.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
65
66
67
68
69
package urlrouter
import "fmt"
const (
ParamCharacter = ':'
WildcardCharacter = '*'
)
var routers map[string]Router
// URLRouter is an interface that must be implemented by a URL router.
type URLRouter interface {
// Lookup returns data and path parameters that associated with path.
// params is a slice of the Param that arranged in the order in which parameters appeared.
// e.g. when built routing path is "/path/:id/:name" and given path is "/path/to/1/alice". params order is [{"id": "1"}, {"name": "alice"}], not [{"name": "alice"}, {"id": "1"}].
// If failed to lookup, data will be nil.
Lookup(path string) (data interface{}, params []Param)
// Build builds URL router from records.
Build(records []Record) error
}
// param represents a name and value of path parameter.
type Param struct {
Name string
Value string
}
// Router is an interface of factory of URLRouter.
type Router interface {
// New returns a new URLRouter.
New() URLRouter
}
// Register registers a Router with name.
func Register(name string, router Router) {
routers[name] = router
}
// NewURLRouter returns the URLRouter with the specified name.
func NewURLRouter(name string) URLRouter {
router, exists := routers[name]
if !exists {
panic(fmt.Errorf("Router named `%v` is not registered", name))
}
return router.New()
}
// Record represents a record data for a router construction.
type Record struct {
// Key for a router construction.
Key string
// Result value for Key.
Value interface{}
}
// NewRecord returns a new Record.
func NewRecord(key string, value interface{}) Record {
return Record{
Key: key,
Value: value,
}
}
func init() {
routers = make(map[string]Router)
}