Redirect www.gvisor.dev to gvisor.dev

This commit is contained in:
Ian Lewis 2019-04-22 01:07:33 -04:00 committed by Ian Lewis
parent c010346c76
commit e986ad2f37
1 changed files with 18 additions and 3 deletions

View File

@ -23,6 +23,7 @@ import (
"net/http" "net/http"
"os" "os"
"regexp" "regexp"
"strings"
) )
var redirects = map[string]string{ var redirects = map[string]string{
@ -56,6 +57,20 @@ func redirectWithQuery(w http.ResponseWriter, r *http.Request, target string) {
http.Redirect(w, r, url, http.StatusFound) http.Redirect(w, r, url, http.StatusFound)
} }
// hostRedirectHandler redirects the www. domain to the naked domain.
func hostRedirectHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.Host, "www.") {
// Redirect to the naked domain.
r.URL.Scheme = "https" // Assume https.
r.URL.Host = r.Host[4:] // Remove the 'www.'
http.Redirect(w, r, r.URL.String(), http.StatusMovedPermanently)
return
}
h.ServeHTTP(w, r)
})
}
// prefixRedirectHandler returns a handler that redirects to the given formated url. // prefixRedirectHandler returns a handler that redirects to the given formated url.
func prefixRedirectHandler(prefix, baseURL string) http.Handler { func prefixRedirectHandler(prefix, baseURL string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@ -89,11 +104,11 @@ func registerRedirects(mux *http.ServeMux) {
for prefix, baseURL := range prefixHelpers { for prefix, baseURL := range prefixHelpers {
p := "/" + prefix + "/" p := "/" + prefix + "/"
mux.Handle(p, prefixRedirectHandler(p, baseURL)) mux.Handle(p, hostRedirectHandler(prefixRedirectHandler(p, baseURL)))
} }
for path, redirect := range redirects { for path, redirect := range redirects {
mux.Handle(path, redirectHandler(redirect)) mux.Handle(path, hostRedirectHandler(redirectHandler(redirect)))
} }
} }
@ -102,7 +117,7 @@ func registerStatic(mux *http.ServeMux, staticDir string) {
if mux == nil { if mux == nil {
mux = http.DefaultServeMux mux = http.DefaultServeMux
} }
mux.Handle("/", http.FileServer(http.Dir(staticDir))) mux.Handle("/", hostRedirectHandler(http.FileServer(http.Dir(staticDir))))
} }
func envFlagString(name, def string) string { func envFlagString(name, def string) string {