-
Notifications
You must be signed in to change notification settings - Fork 0
/
route.go
135 lines (118 loc) · 2.23 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
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
package forest
import (
"bytes"
"errors"
"fmt"
"net/http"
)
type (
routePname struct {
start int
end int
name string
}
Route struct {
Name string
desc string
host string
path string
method string
group *Group
pnames []routePname
handlers []HandlerFunc
}
Routes []*Route
)
func (rs Routes) find(method string) *Route {
for _, r := range rs {
if r.Method() == method {
return r
}
}
return nil
}
func (r *Route) Named(name string, desc ...string) *Route {
prefix := ""
if r.group.Name() != "" {
prefix = r.group.Name() + "."
}
r.Name = prefix + name
if len(desc) > 0 {
r.desc = desc[0]
}
return r
}
func (r *Route) Desc() string {
return r.desc
}
func (r *Route) Host() string {
return r.host
}
func (r *Route) Path() string {
return r.path
}
func (r *Route) Method() string {
return r.method
}
func (r *Route) Handlers() []HandlerFunc {
return r.handlers
}
func (r *Route) Group() *Group {
return r.group
}
func (r *Route) Forest() *Forest {
return r.group.forest
}
func (r *Route) Logger() Logger {
group := r.group
for group != nil {
if group.Logger != nil {
return group.Logger
}
group = group.parent
}
return nil
}
func (r *Route) Render(w http.ResponseWriter, name string, data interface{}) error {
group := r.group
for group != nil {
if group.Renderer != nil {
return group.Renderer.Render(w, name, data)
}
group = group.parent
}
return errors.New("renderer is nil")
}
func (r *Route) ErrorHandle(err error, c Context) {
group := r.group
for group != nil {
if group.ErrorHandler != nil {
group.ErrorHandler(err, c)
return
}
group = group.parent
}
}
func (r *Route) URL(args ...interface{}) string {
if len(args) == 0 {
return r.path
}
uri := new(bytes.Buffer)
path := r.path
lstart := 0
for i, arg := range args {
pname := r.pnames[i]
if pname.start > lstart {
uri.WriteString(path[lstart:pname.start])
}
uri.WriteString(fmt.Sprintf("%v", arg))
lstart = pname.end
}
if lstart < len(path) {
uri.WriteString(path[lstart:])
}
return uri.String()
}
func (r *Route) String() string {
return fmt.Sprintf("[DEBUG] %-6s %s%-36s --> %-18s (%d handlers)\n", r.Method(), r.Host(), r.Path(), r.Name, len(r.Handlers()))
}