本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
1.9KB

  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. //
  27. func CanonicalHost(domain string, code int) func(h http.Handler) http.Handler {
  28. fn := func(h http.Handler) http.Handler {
  29. return canonical{h, domain, code}
  30. }
  31. return fn
  32. }
  33. func (c canonical) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  34. dest, err := url.Parse(c.domain)
  35. if err != nil {
  36. // Call the next handler if the provided domain fails to parse.
  37. c.h.ServeHTTP(w, r)
  38. return
  39. }
  40. if dest.Scheme == "" || dest.Host == "" {
  41. // Call the next handler if the scheme or host are empty.
  42. // Note that url.Parse won't fail on in this case.
  43. c.h.ServeHTTP(w, r)
  44. return
  45. }
  46. if !strings.EqualFold(cleanHost(r.Host), dest.Host) {
  47. // Re-build the destination URL
  48. dest := dest.Scheme + "://" + dest.Host + r.URL.Path
  49. if r.URL.RawQuery != "" {
  50. dest += "?" + r.URL.RawQuery
  51. }
  52. http.Redirect(w, r, dest, c.code)
  53. return
  54. }
  55. c.h.ServeHTTP(w, r)
  56. }
  57. // cleanHost cleans invalid Host headers by stripping anything after '/' or ' '.
  58. // This is backported from Go 1.5 (in response to issue #11206) and attempts to
  59. // mitigate malformed Host headers that do not match the format in RFC7230.
  60. func cleanHost(in string) string {
  61. if i := strings.IndexAny(in, " /"); i != -1 {
  62. return in[:i]
  63. }
  64. return in
  65. }
上海开阖软件有限公司 沪ICP备12045867号-1