github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/handlers/canonical.go (about) 1 package handlers 2 3 import ( 4 "net/url" 5 "strings" 6 7 http "github.com/hxx258456/ccgo/gmhttp" 8 ) 9 10 type canonical struct { 11 h http.Handler 12 domain string 13 code int 14 } 15 16 // CanonicalHost is HTTP middleware that re-directs requests to the canonical 17 // domain. It accepts a domain and a status code (e.g. 301 or 302) and 18 // re-directs clients to this domain. The existing request path is maintained. 19 // 20 // Note: If the provided domain is considered invalid by url.Parse or otherwise 21 // returns an empty scheme or host, clients are not re-directed. 22 // 23 // Example: 24 // 25 // r := mux.NewRouter() 26 // canonical := handlers.CanonicalHost("http://www.gorillatoolkit.org", 302) 27 // r.HandleFunc("/route", YourHandler) 28 // 29 // log.Fatal(http.ListenAndServe(":7000", canonical(r))) 30 // 31 func CanonicalHost(domain string, code int) func(h http.Handler) http.Handler { 32 fn := func(h http.Handler) http.Handler { 33 return canonical{h, domain, code} 34 } 35 36 return fn 37 } 38 39 func (c canonical) ServeHTTP(w http.ResponseWriter, r *http.Request) { 40 dest, err := url.Parse(c.domain) 41 if err != nil { 42 // Call the next handler if the provided domain fails to parse. 43 c.h.ServeHTTP(w, r) 44 return 45 } 46 47 if dest.Scheme == "" || dest.Host == "" { 48 // Call the next handler if the scheme or host are empty. 49 // Note that url.Parse won't fail on in this case. 50 c.h.ServeHTTP(w, r) 51 return 52 } 53 54 if !strings.EqualFold(cleanHost(r.Host), dest.Host) { 55 // Re-build the destination URL 56 dest := dest.Scheme + "://" + dest.Host + r.URL.Path 57 if r.URL.RawQuery != "" { 58 dest += "?" + r.URL.RawQuery 59 } 60 http.Redirect(w, r, dest, c.code) 61 return 62 } 63 64 c.h.ServeHTTP(w, r) 65 } 66 67 // cleanHost cleans invalid Host headers by stripping anything after '/' or ' '. 68 // This is backported from Go 1.5 (in response to issue #11206) and attempts to 69 // mitigate malformed Host headers that do not match the format in RFC7230. 70 func cleanHost(in string) string { 71 if i := strings.IndexAny(in, " /"); i != -1 { 72 return in[:i] 73 } 74 return in 75 }