-
Notifications
You must be signed in to change notification settings - Fork 1
/
override.go
85 lines (74 loc) · 2.3 KB
/
override.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
/*
Copyright 2015 Simon Schmidt
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Override implements a http.Handler, that enables prefix matching based routing.
For example, if you want to serve an static directory using http.FileServer and
http.Dir, but you want to redirect the path "/" to your dynamic main page, and
the path "/wiki/<wiki-page>" to your Wiki, and the path "/<yyyy>/<mm>/<dd>/<title>"
to your blog entrys, you can use "override" to do the job.
*/
package override
import (
"net/http"
"regexp"
)
type Patterned struct{
http.Handler
Prefix string
Exact string
Regexp *regexp.Regexp
}
func (p *Patterned) Match(r *http.Request) bool{
path := r.URL.Path
if p.Prefix!="" {
lpre := len(p.Prefix)
if len(path)<lpre { return false }
return path[:lpre]==p.Prefix
} else if p.Exact!="" {
return path==p.Exact
} else if p.Regexp!=nil {
return p.Regexp.MatchString(path)
}
return false
}
type Overrider struct{
Base http.Handler
Overs []*Patterned
}
func (o *Overrider) Add(prefix string, h http.Handler) {
o.Overs = append(o.Overs,&Patterned{Handler:h,Prefix:prefix})
}
func (o *Overrider) AddExact(exact string, h http.Handler) {
o.Overs = append(o.Overs,&Patterned{Handler:h,Exact:exact})
}
func (o *Overrider) AddRegexp(re string, h http.Handler) error{
rx,err := regexp.Compile(re)
if err!=nil { return err }
o.Overs = append(o.Overs,&Patterned{Handler:h,Regexp:rx})
return nil
}
func (o *Overrider) AddRegexpPOSIX(re string, h http.Handler) error{
rx,err := regexp.CompilePOSIX(re)
if err!=nil { return err }
o.Overs = append(o.Overs,&Patterned{Handler:h,Regexp:rx})
return nil
}
func (o *Overrider) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
for _,p := range o.Overs {
if p.Match(req) {
p.ServeHTTP(resp,req)
return
}
}
o.Base.ServeHTTP(resp,req)
}