/
route.go
64 lines (52 loc) · 1.35 KB
/
route.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
// The Isomorphic Go Project
// Copyright (c) Wirecog, LLC. All rights reserved.
// Use of this source code is governed by a BSD-style
// license, which can be found in the LICENSE file.
package isokit
import (
"context"
"regexp"
"strings"
)
const (
RouteWithParamsPattern = `/([^/]*)`
RouteOnlyPrefixPattern = `/`
RouteSuffixPattern = `/?$`
)
type Handler interface {
ServeRoute(context.Context)
}
type HandlerFunc func(context.Context)
func (f HandlerFunc) ServeRoute(ctx context.Context) {
f(ctx)
}
type RouteVarsKey string
type Route struct {
handler Handler
regex *regexp.Regexp
varNames []string
}
func NewRoute(path string, handler HandlerFunc) *Route {
r := &Route{
handler: handler,
}
path = strings.TrimPrefix(path, `/`)
if strings.HasSuffix(path, `/`) {
path = strings.TrimSuffix(path, `/`)
}
routeParts := strings.Split(path, "/")
var routePattern string = `^`
for _, routePart := range routeParts {
if strings.HasPrefix(routePart, `{`) && strings.HasSuffix(routePart, `}`) {
routePattern += RouteWithParamsPattern
routePart = strings.TrimPrefix(routePart, `{`)
routePart = strings.TrimSuffix(routePart, `}`)
r.varNames = append(r.varNames, routePart)
} else {
routePattern += RouteOnlyPrefixPattern + routePart
}
}
routePattern += RouteSuffixPattern
r.regex = regexp.MustCompile(routePattern)
return r
}