Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 

74 wiersze
1.9 KiB

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