...
1
2
3
4
5
6
7 package redirect
8
9 import (
10 "net/http"
11 "regexp"
12 )
13
14
15
16 func Register(mux *http.ServeMux) {
17 if mux == nil {
18 mux = http.DefaultServeMux
19 }
20
21 mux.HandleFunc("/src/pkg/", srcPkgHandler)
22 }
23
24 func Handler(target string) http.Handler {
25 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
26 url := target
27 if qs := r.URL.RawQuery; qs != "" {
28 url += "?" + qs
29 }
30 http.Redirect(w, r, url, http.StatusMovedPermanently)
31 })
32 }
33
34 var validID = regexp.MustCompile(`^[A-Za-z0-9-]*/?$`)
35
36 func PrefixHandler(prefix, baseURL string) http.Handler {
37 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
38 if p := r.URL.Path; p == prefix {
39
40 http.Redirect(w, r, p[:len(p)-1], http.StatusFound)
41 return
42 }
43 id := r.URL.Path[len(prefix):]
44 if !validID.MatchString(id) {
45 http.Error(w, "Not found", http.StatusNotFound)
46 return
47 }
48 target := baseURL + id
49 http.Redirect(w, r, target, http.StatusFound)
50 })
51 }
52
53
54
55 func srcPkgHandler(w http.ResponseWriter, r *http.Request) {
56 r.URL.Path = "/src/" + r.URL.Path[len("/src/pkg/"):]
57 http.Redirect(w, r, r.URL.String(), http.StatusMovedPermanently)
58 }
59
View as plain text