all repos — homestead @ c7165476f375b097761e729ac14f9b8a68af98c6

Code for my website

domain/content/publisher/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
package publisher

import (
	"context"
	"net/http"

	"alin.ovh/homestead/domain/content/publisher/templates"
	basetpl "alin.ovh/homestead/domain/web/templates"
	ihttp "alin.ovh/homestead/shared/http"
	"tailscale.com/tailcfg"
)

type user struct{}

var (
	ErrCannotDetermineUser = ihttp.NewError("cannot determine user", http.StatusInternalServerError)
	ErrRenderFailure       = ihttp.NewError("failed to render page", http.StatusInternalServerError)
)

func (app *App) WithUserContext(fn ihttp.HandleFunc) ihttp.HandleFunc {
	return func(w http.ResponseWriter, r *http.Request) ihttp.Error {
		ctx := r.Context()
		who, err := app.localClient.WhoIs(ctx, r.RemoteAddr)
		if err != nil {
			return ErrCannotDetermineUser
		}

		return fn(w, r.WithContext(
			context.WithValue(ctx, user{}, who.UserProfile.Clone()),
		))
	}
}

func (app *App) Index(w http.ResponseWriter, r *http.Request) ihttp.Error {
	user := r.Context().Value(user{}).(*tailcfg.UserProfile)
	err := templates.IndexPage(app.siteSettings, templates.PageSettings{
		PageSettings: basetpl.PageSettings{
			Title: "Home",
		},
		User: user.LoginName,
	}).Render(w)
	if err != nil {
		return ErrRenderFailure
	}

	return nil
}

func (app *App) Style(w http.ResponseWriter, r *http.Request) ihttp.Error {
	w.Header().Set("Content-Type", "text/css")
	http.ServeFileFS(w, r, basetpl.Files, "style.css")

	return nil
}