This repository has been archived by the owner on Oct 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrouter.go
118 lines (104 loc) · 2.2 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
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
package wecty
import (
"fmt"
"net/url"
"path"
"syscall/js"
)
func parseHash(s string) (*url.URL, error) {
u, err := url.Parse(s)
if err != nil {
return nil, err
}
if len(u.Fragment) == 0 {
u.Fragment = "/"
}
u, err = url.Parse(u.Fragment)
if err != nil {
return nil, err
}
return u, nil
}
// GetURL ...
func GetURL() *url.URL {
u, _ := parseHash(global.Get("location").Get("href").String())
return u
}
// Router ...
type Router struct {
current *url.URL
f map[string]func(key string)
d map[string]func(key string)
}
// Current ...
func (r *Router) Current() *url.URL {
return r.current
}
// Navigate ...
func (r *Router) Navigate(s string) error {
newURL, err := url.Parse(s)
if err != nil {
return err
}
key := newURL.Path
d, f := path.Split(key)
if len(f) > 0 {
if fn, ok := r.f[key]; ok {
//log.Printf("navigate to: %s", key)
fn(key)
return nil
}
}
if fn, ok := r.d[d]; ok {
//log.Printf("navigate to: %s", d)
fn(key)
return nil
}
return fmt.Errorf("navigate failed: unknown key %q", s)
}
func (r *Router) onHashChange(this js.Value, args []js.Value) interface{} {
oldURL, _ := parseHash(args[0].Get("oldURL").String())
newURL, _ := parseHash(args[0].Get("newURL").String())
if oldURL.String() != newURL.String() {
if err := r.Navigate(newURL.String()); err != nil {
println(err)
RenderBody(NotFoundPage())
}
}
return nil
}
// Handle ...
func (r *Router) Handle(key string, fn func(key string)) {
d, f := path.Split(key)
if len(f) > 0 {
r.f[key] = fn
return
}
r.d[d] = fn
}
// Start ...
func (r *Router) Start() error {
return r.Navigate(r.current.String())
}
// NewRouter ...
func NewRouter() *Router {
r := &Router{f: map[string]func(string){}, d: map[string]func(string){}}
r.current = GetURL()
global.Call("addEventListener", "hashchange", js.FuncOf(r.onHashChange))
return r
}
type defaultNotFoundPage struct {
Core
key string
}
func (c *defaultNotFoundPage) Render() HTML {
return Tag("body", Tag("h1", Text("Not Found: "+c.key)))
}
// NotFoundPage ...
func NotFoundPage() Component {
return &defaultNotFoundPage{key: GetURL().String()}
}
// Navigate ...
func Navigate(s string) {
global.Get("location").Set("href", "#"+s)
}