Redirect HTTP requests to HTTPS
(toPort string)
| 224 | |
| 225 | // Redirect HTTP requests to HTTPS |
| 226 | func tlsRedirect(toPort string) http.HandlerFunc { |
| 227 | if toPort == ":443" || toPort == ":https" { |
| 228 | toPort = "" |
| 229 | } else if toPort != "" && toPort[:1] == ":" { |
| 230 | // Strip leading colon. JoinHostPort will add it back. |
| 231 | toPort = toPort[1:] |
| 232 | } |
| 233 | |
| 234 | return func(wrt http.ResponseWriter, req *http.Request) { |
| 235 | host, _, err := net.SplitHostPort(req.Host) |
| 236 | if err != nil { |
| 237 | // If SplitHostPort has failed assume it's because :port part is missing. |
| 238 | host = req.Host |
| 239 | } |
| 240 | |
| 241 | target, _ := url.ParseRequestURI(req.RequestURI) |
| 242 | target.Scheme = "https" |
| 243 | |
| 244 | // Ensure valid redirect target. |
| 245 | if toPort != "" { |
| 246 | // Replace the port number. |
| 247 | target.Host = net.JoinHostPort(host, toPort) |
| 248 | } else { |
| 249 | target.Host = host |
| 250 | } |
| 251 | |
| 252 | if target.Path == "" { |
| 253 | target.Path = "/" |
| 254 | } |
| 255 | |
| 256 | http.Redirect(wrt, req, target.String(), http.StatusTemporaryRedirect) |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | // Wrapper for adding optional HTTP headers: |
| 261 | // - Strict-Transport-Security |
no test coverage detected
searching dependent graphs…