forked from bmizerany/pat
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmux.go
98 lines (85 loc) · 2.09 KB
/
mux.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
// pat.go a sinatra like muxer for go.
package pat
import (
"net/http"
"net/url"
)
type PatternServeMux struct {
handlers map[string][]*patHandler
}
// Creates an new *PatternServeMux.
func New() *PatternServeMux {
return &PatternServeMux{make(map[string][]*patHandler)}
}
// Implements HttpHandler.
func (p *PatternServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for _, ph := range p.handlers[r.Method] {
if params, ok := ph.try(r.URL.Path); ok {
if len(params) > 0 {
r.URL.RawQuery = url.Values(params).Encode() + "&" + r.URL.RawQuery
}
ph.ServeHTTP(w, r)
return
}
}
http.NotFound(w, r)
}
// Adds the pattern handler pair for a Get.
func (p *PatternServeMux) Get(pat string, h http.Handler) {
p.Add("GET", pat, h)
}
// Adds the pattern handler pair for a Post.
func (p *PatternServeMux) Post(pat string, h http.Handler) {
p.Add("POST", pat, h)
}
// Adds the pattern handler pair for a Put.
func (p *PatternServeMux) Put(pat string, h http.Handler) {
p.Add("PUT", pat, h)
}
// Adds the pattern handler pair for a Delete.
func (p *PatternServeMux) Del(pat string, h http.Handler) {
p.Add("DELETE", pat, h)
}
// Adds the pattern handler pair for a HTTP Method meth.
func (p *PatternServeMux) Add(meth, pat string, h http.Handler) {
p.handlers[meth] = append(p.handlers[meth], &patHandler{pat, h})
}
type patHandler struct {
pat string
http.Handler
}
func (ph *patHandler) try(path string) (url.Values, bool) {
p := make(url.Values)
var i, j int
for i < len(path) {
switch {
case j == len(ph.pat) && ph.pat[j-1] == '/':
// Should i put a special form variable splat for this case
p.Add(":splat", path[i:])
return p, true
case j >= len(ph.pat):
return nil, false
case ph.pat[j] == ':':
var name, val string
name, j = find(ph.pat, '/', j)
val, i = find(path, '/', i)
p.Add(name, val)
case path[i] == ph.pat[j]:
i++
j++
default:
return nil, false
}
}
if j != len(ph.pat) {
return nil, false
}
return p, true
}
func find(s string, c byte, i int) (string, int) {
j := i
for j < len(s) && s[j] != c {
j++
}
return s[i:j], j
}