...

Source file src/golang.org/x/tools/godoc/redirect/redirect.go

Documentation: golang.org/x/tools/godoc/redirect

     1  // Copyright 2013 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package redirect provides hooks to register HTTP handlers that redirect old
     6  // godoc paths to their new equivalents.
     7  package redirect // import "golang.org/x/tools/godoc/redirect"
     8  
     9  import (
    10  	"net/http"
    11  	"regexp"
    12  )
    13  
    14  // Register registers HTTP handlers that redirect old godoc paths to their new equivalents.
    15  // If mux is nil it uses http.DefaultServeMux.
    16  func Register(mux *http.ServeMux) {
    17  	if mux == nil {
    18  		mux = http.DefaultServeMux
    19  	}
    20  	// NB: /src/pkg (sans trailing slash) is the index of packages.
    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  			// redirect /prefix/ to /prefix
    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  // Redirect requests from the old "/src/pkg/foo" to the new "/src/foo".
    54  // See http://golang.org/s/go14nopkg
    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