all repos — homestead @ 628ce84dd6f2c7baf327f22267cb1bcc45271ab5

Code for my website

domain/web/mux.go (view raw)

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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package website

import (
	"net/http"
	"net/url"
	"regexp"
	"slices"
	"strings"

	"github.com/kevinpollet/nego"

	"alin.ovh/homestead/domain/analytics"
	calendar "alin.ovh/homestead/domain/calendar/templates"
	"alin.ovh/homestead/domain/web/server"
	"alin.ovh/homestead/domain/web/templates"
	ihttp "alin.ovh/homestead/shared/http"
)

var (
	ErrCanonPath     = ihttp.NewError("Error canonicalising path", http.StatusInternalServerError)
	ErrReadingFile   = ihttp.NewError("Error reading file", http.StatusInternalServerError)
	ErrNotFound      = ihttp.NewError("File not found", http.StatusNotFound)
	ErrRenderFailure = ihttp.NewError("Error rendering template", http.StatusInternalServerError)
	feedHeaders      = map[string]string{
		"Access-Control-Allow-Origin":  "*",
		"Access-Control-Allow-Methods": "GET, OPTIONS",
		"Access-Control-Max-Age":       "3600",
	}
)

func (website *Website) ErrorHandler(err error, w http.ResponseWriter, r *http.Request) {
	hErr, ok := err.(ihttp.Error)
	if !ok {
		hErr = ihttp.NewError(err.Error(), http.StatusInternalServerError)
	}
	if strings.Contains(r.Header.Get("Accept"), "text/html") {
		w.WriteHeader(hErr.StatusCode())
		err := templates.Error(*website.siteSettings, hErr).Render(w)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	} else {
		http.Error(w, hErr.Error(), hErr.StatusCode())
	}
}

func (website *Website) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
	urlPath := r.URL.Path
	if r.URL.Query().Has("go-get") && r.URL.Query().Get("go-get") == "1" {
		var err error
		urlPath, err = url.JoinPath("/go", r.URL.Path)
		if err != nil {
			return ErrCanonPath.WithCause(err)
		}
	}
	urlPath, shouldRedirect := website.reader.CanonicalisePath(urlPath)
	if shouldRedirect {
		http.Redirect(w, r, urlPath, http.StatusFound)

		return nil
	}
	file, err := website.reader.GetFile(urlPath)
	if err != nil {
		website.log.Warn("Error reading file", "error", err)

		return ErrReadingFile.WithCause(err)
	}
	if file == nil {
		return ErrNotFound
	}
	analytics.WithTitle(r, file.Title)
	w.Header().Add("ETag", file.Etag)
	w.Header().Add("Vary", "Accept-Encoding")
	for k, v := range ExtraHeaders {
		w.Header().Add(k, v)
	}
	enc := nego.NegotiateContentEncoding(r, file.AvailableEncodings()...)
	if enc != "" {
		w.Header().Add("Content-Encoding", enc)
	}
	w.Header().Add("Content-Type", file.ContentType)

	if file.ContentType == "application/xml" {
		for k, v := range feedHeaders {
			w.Header().Add(k, v)
		}
	}
	http.ServeContent(w, r, file.Path, file.LastModified, file.Encodings[enc])

	return nil
}

func (website *Website) Calendar(w http.ResponseWriter, r *http.Request) error {
	analytics.WithTitle(r, "Calendar")
	err := calendar.CalendarPage(*website.siteSettings, website.calendar).Render(w)
	if err != nil {
		return ErrRenderFailure.WithCause(err)
	}

	return nil
}

func (website *Website) MakeRedirectorApp() *server.App {
	mux := ihttp.NewServeMux(website.log.Named("http"))
	website.identity.RegisterHandlers(mux)

	re := regexp.MustCompile(
		"^(.*)\\." + strings.ReplaceAll(website.config.WildcardDomain, ".", `\.`) + "$",
	)
	replace := "${1}." + website.config.Domains[0]
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) error {
		switch {
		case r.URL.Query().Has("go-get") && r.URL.Query().Get("go-get") == "1":
			return website.ServeHTTP(w, r)
		case slices.Contains(website.config.Domains, r.Host):
			path, _ := website.reader.CanonicalisePath(r.URL.Path)
			ihttp.PermanentRedirect(w, r, website.config.BaseURL.JoinPath(path))
		case re.MatchString(r.Host):
			url := website.config.BaseURL.JoinPath()
			url.Host = re.ReplaceAllString(r.Host, replace)
			ihttp.TemporaryRedirect(w, r, url)
		case true:
			http.NotFound(w, r)
		}

		return nil
	})

	return &server.App{
		WildcardDomain: website.config.WildcardDomain,
		Domains:        website.config.Domains,
		Handler:        mux,
	}
}