2013-10-01 10:32:13 +04:00
|
|
|
// Copyright 2013 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2013-10-02 07:13:34 +04:00
|
|
|
// Package redirect provides hooks to register HTTP handlers that redirect old
|
2021-03-12 21:54:13 +03:00
|
|
|
// godoc paths to their new equivalents.
|
2014-12-09 07:00:58 +03:00
|
|
|
package redirect // import "golang.org/x/tools/godoc/redirect"
|
2013-10-01 10:32:13 +04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"regexp"
|
|
|
|
)
|
|
|
|
|
2021-03-12 21:54:13 +03:00
|
|
|
// Register registers HTTP handlers that redirect old godoc paths to their new equivalents.
|
|
|
|
// If mux is nil it uses http.DefaultServeMux.
|
2013-10-02 07:13:34 +04:00
|
|
|
func Register(mux *http.ServeMux) {
|
|
|
|
if mux == nil {
|
|
|
|
mux = http.DefaultServeMux
|
|
|
|
}
|
2014-09-10 17:02:54 +04:00
|
|
|
// NB: /src/pkg (sans trailing slash) is the index of packages.
|
2014-11-24 05:25:05 +03:00
|
|
|
mux.HandleFunc("/src/pkg/", srcPkgHandler)
|
2013-10-01 10:32:13 +04:00
|
|
|
}
|
|
|
|
|
2013-10-02 07:13:34 +04:00
|
|
|
func Handler(target string) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2015-10-06 06:00:21 +03:00
|
|
|
url := target
|
|
|
|
if qs := r.URL.RawQuery; qs != "" {
|
|
|
|
url += "?" + qs
|
|
|
|
}
|
|
|
|
http.Redirect(w, r, url, http.StatusMovedPermanently)
|
2013-10-02 07:13:34 +04:00
|
|
|
})
|
2013-10-01 10:32:13 +04:00
|
|
|
}
|
|
|
|
|
2019-11-21 06:43:00 +03:00
|
|
|
var validID = regexp.MustCompile(`^[A-Za-z0-9-]*/?$`)
|
2013-10-01 10:32:13 +04:00
|
|
|
|
2013-10-02 07:13:34 +04:00
|
|
|
func PrefixHandler(prefix, baseURL string) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2013-10-01 10:32:13 +04:00
|
|
|
if p := r.URL.Path; p == prefix {
|
|
|
|
// redirect /prefix/ to /prefix
|
|
|
|
http.Redirect(w, r, p[:len(p)-1], http.StatusFound)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
id := r.URL.Path[len(prefix):]
|
2019-11-21 06:43:00 +03:00
|
|
|
if !validID.MatchString(id) {
|
2013-10-01 10:32:13 +04:00
|
|
|
http.Error(w, "Not found", http.StatusNotFound)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
target := baseURL + id
|
|
|
|
http.Redirect(w, r, target, http.StatusFound)
|
2013-10-02 07:13:34 +04:00
|
|
|
})
|
2013-10-01 10:32:13 +04:00
|
|
|
}
|
2014-09-10 17:02:54 +04:00
|
|
|
|
|
|
|
// Redirect requests from the old "/src/pkg/foo" to the new "/src/foo".
|
|
|
|
// See http://golang.org/s/go14nopkg
|
|
|
|
func srcPkgHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
r.URL.Path = "/src/" + r.URL.Path[len("/src/pkg/"):]
|
|
|
|
http.Redirect(w, r, r.URL.String(), http.StatusMovedPermanently)
|
|
|
|
}
|