all repos — homestead @ db6f2461ccd1e17e620451aab958068f6ca1664e

Code for my website

internal/website/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
package website

import (
	"encoding/json"
	"net/http"
	"strings"

	"go.alanpearce.eu/website/internal/config"
	ihttp "go.alanpearce.eu/website/internal/http"
	"go.alanpearce.eu/website/internal/storage/files"
	"go.alanpearce.eu/website/templates"
	"go.alanpearce.eu/x/log"

	"github.com/benpate/digit"
	"github.com/kevinpollet/nego"
)

type webHandler func(http.ResponseWriter, *http.Request) *ihttp.Error

type WrappedWebHandler struct {
	config  *config.Config
	handler webHandler
	log     *log.Logger
}

func wrapHandler(cfg *config.Config, webHandler webHandler, log *log.Logger) WrappedWebHandler {
	return WrappedWebHandler{
		config:  cfg,
		handler: webHandler,
		log:     log,
	}
}

func (fn WrappedWebHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	defer func() {
		if fail := recover(); fail != nil {
			w.WriteHeader(http.StatusInternalServerError)
			fn.log.Error("runtime panic!", "error", fail)
		}
	}()
	if err := fn.handler(w, r); err != nil {
		if strings.Contains(r.Header.Get("Accept"), "text/html") {
			w.WriteHeader(err.Code)
			err := templates.Error(fn.config, r.URL.Path, err).Render(r.Context(), w)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
		} else {
			http.Error(w, err.Message, err.Code)
		}
	}
}

func NewMux(
	cfg *config.Config,
	reader *files.Reader,
	log *log.Logger,
) (mux *http.ServeMux, err error) {
	mux = &http.ServeMux{}
	templates.Setup()

	mux.Handle("/", wrapHandler(cfg, func(w http.ResponseWriter, r *http.Request) *ihttp.Error {
		urlPath, shouldRedirect := reader.CanonicalisePath(r.URL.Path)
		if shouldRedirect {
			http.Redirect(w, r, urlPath, 302)

			return nil
		}
		file, err := reader.GetFile(urlPath)
		if err != nil {
			return &ihttp.Error{
				Message: "Error reading file",
				Code:    http.StatusInternalServerError,
			}
		}
		if file == nil {
			return &ihttp.Error{
				Message: "File not found",
				Code:    http.StatusNotFound,
			}
		}
		w.Header().Add("ETag", file.Etag)
		w.Header().Add("Vary", "Accept-Encoding")
		w.Header().Add("Content-Security-Policy", cfg.CSP.String())
		for k, v := range cfg.Extra.Headers {
			w.Header().Add(k, v)
		}
		enc := nego.NegotiateContentEncoding(r, file.AvailableEncodings()...)
		switch enc {
		case "br", "gzip":
			w.Header().Add("Content-Encoding", enc)
		}
		w.Header().Add("Content-Type", file.ContentType)
		http.ServeContent(w, r, file.Path, file.LastModified, file.Encodings[enc])

		return nil
	}, log))

	var acctResource = "acct:" + cfg.Email
	me := digit.NewResource(acctResource).
		Link("http://openid.net/specs/connect/1.0/issuer", "", cfg.OIDCHost.String())

	mux.HandleFunc("/.well-known/webfinger", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Query().Get("resource") == acctResource {
			obj, err := json.Marshal(me)
			if err != nil {
				http.Error(
					w,
					http.StatusText(http.StatusInternalServerError),
					http.StatusInternalServerError,
				)

				return
			}

			w.Header().Add("Content-Type", "application/jrd+json")
			w.Header().Add("Access-Control-Allow-Origin", "*")
			_, err = w.Write(obj)
			if err != nil {
				log.Warn("error writing webfinger request", "error", err)
			}
		}
	})
	const oidcPath = "/.well-known/openid-configuration"
	mux.HandleFunc(
		oidcPath,
		func(w http.ResponseWriter, r *http.Request) {
			u := cfg.OIDCHost.JoinPath(oidcPath)
			http.Redirect(w, r, u.String(), 302)
		})

	return mux, nil
}