-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttps_redirect.go
45 lines (37 loc) · 957 Bytes
/
https_redirect.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package middleware
import (
"fmt"
"net"
"net/http"
"darvaza.org/core"
"darvaza.org/middleware/internal"
)
// HTTPSRedirectHandler provides an automatic redirect to HTTPS
type HTTPSRedirectHandler struct {
Port int
}
func (h *HTTPSRedirectHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if req.URL.Scheme != "https" {
url := *req.URL
url.Scheme = "https"
host, _, _ := core.SplitHostPort(req.Host)
if h.Port != 0 && h.Port != 443 {
port := fmt.Sprintf("%v", h.Port)
url.Host = net.JoinHostPort(host, port)
} else {
url.Host = host
}
loc := url.String()
rw.Header().Add("Location", loc)
rw.WriteHeader(http.StatusPermanentRedirect)
internal.Fprintf(rw, "Redirected to %s", loc)
} else {
http.NotFound(rw, req)
}
}
// NewHTTPSRedirectHandler creates a new automatic redirect to HTTPS handler
func NewHTTPSRedirectHandler(port int) http.Handler {
return &HTTPSRedirectHandler{
Port: port,
}
}