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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
package uniqueDomain
import (
"net"
"net/http"
"strings"
"gitlab.com/gitlab-org/gitlab-pages/internal/domain"
"gitlab.com/gitlab-org/gitlab-pages/internal/logging"
)
func NewMiddleware(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
uniqueURL := getUniqueURL(r)
if uniqueURL == "" {
logging.
LogRequest(r).
WithField("uniqueURL", uniqueURL).
Debug("unique domain: doing nothing")
handler.ServeHTTP(w, r)
return
}
logging.
LogRequest(r).
WithField("uniqueURL", uniqueURL).
Info("redirecting to unique domain")
http.Redirect(w, r, uniqueURL, http.StatusPermanentRedirect)
})
}
func getUniqueURL(r *http.Request) string {
domain := domain.FromRequest(r)
lookupPath, err := domain.GetLookupPath(r)
if err != nil {
logging.
LogRequest(r).
WithError(err).
Error("uniqueDomain: failed to get lookupPath")
return ""
}
// No uniqueHost to redirect
if lookupPath.UniqueHost == "" {
return ""
}
requestHost, port, err := net.SplitHostPort(r.Host)
if err != nil {
requestHost = r.Host
}
// Already serving the uniqueHost
if lookupPath.UniqueHost == requestHost {
return ""
}
uniqueURL := *r.URL
if port == "" {
uniqueURL.Host = lookupPath.UniqueHost
} else {
uniqueURL.Host = net.JoinHostPort(lookupPath.UniqueHost, port)
}
// Ensure to redirect to the same path requested
uniqueURL.Path = strings.TrimPrefix(
r.URL.Path,
strings.TrimSuffix(lookupPath.Prefix, "/"),
)
return uniqueURL.String()
}
|