/
goweb.go
64 lines (58 loc) · 1.36 KB
/
goweb.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
package goweb
import (
"net/http"
"regexp"
)
type Any interface{}
type Responder func(http.ResponseWriter, *http.Request, Result, ...string) Result
type Result struct {
Final bool
State map[string]Any
}
// Or composes Routers by returning the first final Result of the Routers.
func Or(rs ...Responder) Responder {
return func(w http.ResponseWriter, c *http.Request, s Result, _ ...string) Result {
for _, r := range rs {
s = r(w, c, s)
if s.Final {
return s
}
}
return s
}
}
// Route returns a new router that matches the pat against
// the url that is passed in.
func Route(pat string, f Responder) Responder {
r, err := regexp.Compile("^" + pat + "$")
if err != nil {
panic(err)
}
return func(w http.ResponseWriter, c *http.Request, s Result, _ ...string) Result {
path := MatchUrl(r, c.URL.Path)
if path != nil {
s.Final = true
f(w, c, s, path...)
return s
}
s.Final = false
return s
}
}
// MatchUrl returns the list of submatches of r
func MatchUrl(r *regexp.Regexp, against string) []string {
if x := r.FindStringSubmatch(against); x != nil {
return x[1:]
}
return nil
}
// Pass sets s.Final to false
func Pass(s *Result) {
s.Final = false
}
func Handler(route Responder) http.HandlerFunc {
return func(w http.ResponseWriter, c *http.Request) {
s := Result{Final: false, State: make(map[string]Any)}
route(w, c, s)
}
}