-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute.go
85 lines (74 loc) · 1.56 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
package gong
import (
"context"
"io"
)
type Route interface {
Route(path string, view View, f func(r Route))
}
type route struct {
gong *Gong
path string
view View
actions map[string]Action
children map[string]*route
defaultChild *route
parent *route
}
func (r *route) Route(path string, view View, f func(r Route)) {
newRoute := &route{
gong: r.gong,
view: view,
path: r.path + path,
actions: make(map[string]Action),
children: make(map[string]*route),
parent: r,
}
r.addChild(newRoute.path, newRoute)
r.gong.handleRoute(newRoute)
if f != nil {
f(newRoute)
}
}
func (r *route) Render(ctx context.Context, w io.Writer) error {
gCtx := getContext(ctx)
gCtx.route = r
if loader, ok := r.view.(Loader); ok {
gCtx.loader = loader
}
if gCtx.action {
if action, ok := r.actions[gCtx.kind]; ok {
gCtx.loader = nil
if loader, ok := action.(Loader); ok {
gCtx.loader = loader
}
return render(ctx, gCtx, w, action.Action())
}
if action, ok := r.view.(Action); ok {
return render(ctx, gCtx, w, action.Action())
}
return nil
}
return render(ctx, gCtx, w, r.view.View())
}
func (r *route) addChild(path string, child *route) {
r.children[path] = child
if r.defaultChild == nil {
r.defaultChild = child
}
if r.parent != nil {
r.parent.addChild(path, r)
}
}
func (r *route) getRoute(path string) *route {
if r.path == path {
return r
}
return r.children[path].getRoute(path)
}
func (r *route) getRoot() *route {
if r.parent == nil {
return r
}
return r.parent
}