File
Blob: gateway/http.go
| 1 | package gateway |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "net" |
| 6 | "net/http" |
| 7 | |
| 8 | "github.com/go-chi/chi/v5" |
| 9 | ) |
| 10 | |
| 11 | // taken from certmagic/certmagic.go |
| 12 | |
| 13 | func hostOnly(hostport string) string { |
| 14 | host, _, err := net.SplitHostPort(hostport) |
| 15 | if err != nil { |
| 16 | return hostport // OK; probably had no port to begin with |
| 17 | } |
| 18 | return host |
| 19 | } |
| 20 | |
| 21 | func (g *Gateway) httpRedirect(w http.ResponseWriter, r *http.Request) { |
| 22 | toURL := "https://" |
| 23 | |
| 24 | // since we redirect to the standard HTTPS port, we |
| 25 | // do not need to include it in the redirect URL |
| 26 | requestHost := hostOnly(r.Host) |
| 27 | |
| 28 | toURL += requestHost |
| 29 | if g.GatewayPort != 443 { |
| 30 | toURL = fmt.Sprintf("%s:%d", toURL, g.GatewayPort) |
| 31 | } |
| 32 | toURL += r.URL.RequestURI() |
| 33 | |
| 34 | // get rid of this disgusting unencrypted HTTP connection 🤢 |
| 35 | w.Header().Set("Connection", "close") |
| 36 | |
| 37 | http.Redirect(w, r, toURL, http.StatusMovedPermanently) |
| 38 | } |
| 39 | |
| 40 | func (g *Gateway) httpRouter() http.Handler { |
| 41 | r := chi.NewRouter() |
| 42 | |
| 43 | r.Connect("/", g.httpConnect) |
| 44 | r.Handle("/*", http.HandlerFunc(g.httpRedirect)) |
| 45 | |
| 46 | return r |
| 47 | } |