-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.go
More file actions
57 lines (46 loc) · 1.34 KB
/
route.go
File metadata and controls
57 lines (46 loc) · 1.34 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
package router
import (
"fmt"
"net/http"
"regexp"
"strings"
)
type Route struct {
method string
pathRegexp *regexp.Regexp
handler http.Handler
}
// Handler sets a handler for the route.
func (this *Route) Handler(handler http.Handler) *Route {
this.handler = handler
return this
}
// HandlerFunc sets a handler function for the route.
func (this *Route) HandlerFunc(f func(http.ResponseWriter, *http.Request)) *Route {
return this.Handler(http.HandlerFunc(f))
}
func (this *Route) PathPrefix(template string) *Route {
r := regexp.MustCompile(`{[^/#?()\.\\]+}`)
tmpRegx := r.ReplaceAllStringFunc(template, func(m string) string {
m = m[1 : len(m)-1]
return fmt.Sprintf(`(?P<%s>[^/#?]+)`, m)
})
this.pathRegexp = regexp.MustCompile("^" + tmpRegx + ".*$")
return this
}
// Path defines URL template for the route.
// It accepts a template with zero or more URL variables enclosed by {}.
func (this *Route) Path(template string) *Route {
r := regexp.MustCompile(`{[^/#?()\.\\]+}`)
tmpRegx := r.ReplaceAllStringFunc(template, func(m string) string {
m = m[1 : len(m)-1]
return fmt.Sprintf(`(?P<%s>[^/#?]+)`, m)
})
this.pathRegexp = regexp.MustCompile("^" + tmpRegx + "$")
return this
}
// Method sets a method for the route.
func (this *Route) Method(method string) *Route {
this.method = strings.ToUpper(method)
return this
}