generated from fun-stack/example
-
Notifications
You must be signed in to change notification settings - Fork 4
/
canonicaldomain.go
42 lines (36 loc) · 1.13 KB
/
canonicaldomain.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
package main
import (
"fmt"
"net/http"
"strings"
"github.com/johnwarden/httperror"
)
var nonCanonicalDomains = map[string]string{
"social-protocols-news.fly.dev": "news.social-protocols.org",
"127.0.0.1:8080": "localhost:8080", // just for testing
}
var canonicalDomains = getValues(nonCanonicalDomains)
func (app app) canonicalDomainMiddleware(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Redirect any non-canonical domain to the corresponding canonical domain.
for nonCanonicalDomain, canonicalDomain := range nonCanonicalDomains {
if r.Host == nonCanonicalDomain {
url := "https://" + canonicalDomain + r.RequestURI
http.Redirect(w, r, url, http.StatusMovedPermanently)
return
}
}
isCanonical := false
for _, canonicalDomain := range canonicalDomains {
if strings.HasPrefix(r.Host, canonicalDomain) {
isCanonical = true
break
}
}
if !isCanonical {
httperror.DefaultErrorHandler(w, httperror.New(http.StatusForbidden, fmt.Sprintf("Invalid request host: %s", r.Host)))
return
}
handler.ServeHTTP(w, r)
})
}