package middleware import ( "net/http" "strings" ) // ForwardedHeaders sets r.URL.Scheme and r.URL.Host from reverse-proxy headers so // chi RedirectSlashes and other absolute redirects use https behind Cloudflare/nginx. func ForwardedHeaders(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if proto := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")); proto != "" { if i := strings.IndexByte(proto, ','); i >= 0 { proto = strings.TrimSpace(proto[:i]) } r.URL.Scheme = proto } if host := strings.TrimSpace(r.Header.Get("X-Forwarded-Host")); host != "" { if i := strings.IndexByte(host, ','); i >= 0 { host = strings.TrimSpace(host[:i]) } r.URL.Host = host } else if r.Host != "" { r.URL.Host = r.Host } next.ServeHTTP(w, r) }) }