www-pgs.diff

on erock's pastes | raw

expires: 30 May, 2024

 1diff --git a/pgs/api.go b/pgs/api.go
 2index 51a566d..2b81870 100644
 3--- a/pgs/api.go
 4+++ b/pgs/api.go
 5@@ -458,9 +458,9 @@ func createSubdomainRoutes(hasPerm HasPerm) []shared.Route {
 6 	imgRequest := ImgAssetRequest(hasPerm)
 7 
 8 	return []shared.Route{
 9-		shared.NewRoute("GET", "/", assetRequest),
10-		shared.NewRoute("GET", "(/.+.(?:jpg|jpeg|png|gif|webp|svg))(/.+)", imgRequest),
11-		shared.NewRoute("GET", "/(.+)", assetRequest),
12+		shared.NewRoute("GET", "/", shared.WwwRedirect(assetRequest)),
13+		shared.NewRoute("GET", "(/.+.(?:jpg|jpeg|png|gif|webp|svg))(/.+)", shared.WwwRedirect(imgRequest)),
14+		shared.NewRoute("GET", "/(.+)", shared.WwwRedirect(assetRequest)),
15 	}
16 }
17 
18diff --git a/shared/router.go b/shared/router.go
19index 4dbd76d..c958815 100644
20--- a/shared/router.go
21+++ b/shared/router.go
22@@ -43,7 +43,24 @@ func CreatePProfRoutes(routes []Route) []Route {
23 	)
24 }
25 
26-type ServeFn func(http.ResponseWriter, *http.Request)
27+func WwwRedirect(serve http.HandlerFunc) http.HandlerFunc {
28+	return func(w http.ResponseWriter, r *http.Request) {
29+		if !strings.HasPrefix(r.Host, "www.") {
30+			serve(w, r)
31+			return
32+		}
33+
34+		logger := GetLogger(r)
35+		url := strings.Replace(r.Host, "www.", "", 1)
36+		logger.Info(
37+			"redirecting",
38+			"host", r.Host,
39+			"url", url,
40+		)
41+		http.Redirect(w, r, url, http.StatusMovedPermanently)
42+	}
43+}
44+
45 type HttpCtx struct {
46 	Cfg     *ConfigSite
47 	Dbpool  db.DB
48@@ -154,7 +171,12 @@ func GetSubdomain(r *http.Request) string {
49 }
50 
51 func GetCustomDomain(host string, space string) string {
52-	txt := fmt.Sprintf("_%s.%s", space, host)
53+	finhost := host
54+	if strings.HasPrefix(host, "www.") {
55+		finhost = strings.Replace(host, "www.", "", 1)
56+	}
57+
58+	txt := fmt.Sprintf("_%s.%s", space, finhost)
59 	records, err := net.LookupTXT(txt)
60 	if err != nil {
61 		return ""