aboutsummaryrefslogtreecommitdiff
path: root/internal/domain_redirect.go
blob: fe8bc1c4ee5b2c196455cad14e9941dfaff9bcff (plain)
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
package internal

import (
	"flag"
	"fmt"
	"net/http"
	"strings"
)

var (
	redirectDomain = flag.String("redirect-domain", "xeiaso.net", "Domain to redirect to")

	allowedPaths = map[string]struct{}{
		"/blog.rss":  {},
		"/blog.atom": {},
		"/blog.json": {},
	}
)

func DomainRedirect(next http.Handler, development bool) http.Handler {
	if development {
		return next
	}

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if _, ok := allowedPaths[r.URL.Path]; ok {
			next.ServeHTTP(w, r)
			return
		}

		if r.Host != *redirectDomain {
			if !strings.HasSuffix(r.Host, ".onion") {
				if r.Method != "GET" {
					http.Error(w, fmt.Sprintf("go to https://%s%s and try your request again", *redirectDomain, r.RequestURI), http.StatusMisdirectedRequest)
					return
				}
				http.Redirect(w, r, fmt.Sprintf("https://%s%s", *redirectDomain, r.RequestURI), http.StatusMovedPermanently)
				return
			}
		}

		next.ServeHTTP(w, r)
	})
}