gitea

Development moved to Codeberg

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 62
  63. 63
  64. 64
  65. 65
  66. 66
  67. 67
  68. 68
  69. 69
  70. 70
  71. 71
  72. 72
  73. 73
  74. 74
package handlers

import (
	"net/http"
	"net/url"
	"strings"
)

type canonical struct {
	h      http.Handler
	domain string
	code   int
}

// CanonicalHost is HTTP middleware that re-directs requests to the canonical
// domain. It accepts a domain and a status code (e.g. 301 or 302) and
// re-directs clients to this domain. The existing request path is maintained.
//
// Note: If the provided domain is considered invalid by url.Parse or otherwise
// returns an empty scheme or host, clients are not re-directed.
//
// Example:
//
//  r := mux.NewRouter()
//  canonical := handlers.CanonicalHost("http://www.gorillatoolkit.org", 302)
//  r.HandleFunc("/route", YourHandler)
//
//  log.Fatal(http.ListenAndServe(":7000", canonical(r)))
//
func CanonicalHost(domain string, code int) func(h http.Handler) http.Handler {
	fn := func(h http.Handler) http.Handler {
		return canonical{h, domain, code}
	}

	return fn
}

func (c canonical) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	dest, err := url.Parse(c.domain)
	if err != nil {
		// Call the next handler if the provided domain fails to parse.
		c.h.ServeHTTP(w, r)
		return
	}

	if dest.Scheme == "" || dest.Host == "" {
		// Call the next handler if the scheme or host are empty.
		// Note that url.Parse won't fail on in this case.
		c.h.ServeHTTP(w, r)
		return
	}

	if !strings.EqualFold(cleanHost(r.Host), dest.Host) {
		// Re-build the destination URL
		dest := dest.Scheme + "://" + dest.Host + r.URL.Path
		if r.URL.RawQuery != "" {
			dest += "?" + r.URL.RawQuery
		}
		http.Redirect(w, r, dest, c.code)
		return
	}

	c.h.ServeHTTP(w, r)
}

// cleanHost cleans invalid Host headers by stripping anything after '/' or ' '.
// This is backported from Go 1.5 (in response to issue #11206) and attempts to
// mitigate malformed Host headers that do not match the format in RFC7230.
func cleanHost(in string) string {
	if i := strings.IndexAny(in, " /"); i != -1 {
		return in[:i]
	}
	return in
}