summaryrefslogtreecommitdiffstats
path: root/roseh.moe.go
blob: ad09cb5cd76a411d896e2b78a5d3f7c8cb15116e (plain) (blame)
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package main

import (
	"bytes"
	"embed"
	"flag"
	"fmt"
	"html/template"
	"io"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"slices"
	"strings"
	"time"
)

var (
	port  = flag.Int("port", 42069, "port to listen on")
	https = flag.Bool("https", false, "use https")

	serverStartTime = time.Now()
)

//go:embed templates/404.html.template
var notFoundString string

var notFoundTemplate = template.Must(template.New("notFound").Parse(notFoundString))

func notFound(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusNotFound)
	type args struct {
		Path string
	}
	if err := notFoundTemplate.Execute(w, args{Path: r.URL.Path}); err != nil {
		log.Printf("Warning: notFound: %s", err)
	}
}

//go:embed templates/outline.html.template
var outlineString string

var outlineTemplate = template.Must(template.New("outline").Parse(outlineString))

var (
	//go:embed templates/blog/post.html.template
	postString string

	//go:embed templates/blog/posts
	blogPostFiles embed.FS
)

func preloadBlogPosts() map[string][]byte {
	base, err := outlineTemplate.Clone()
	if err != nil {
		log.Fatalf("outlineTemplate.Clone: %s", err)
	}
	base, err = base.New("body").Parse(postString)
	if err != nil {
		log.Fatalf("post.html.template: invalid template: %s", err)
	}
	postTemplates, err := blogPostFiles.ReadDir("templates/blog/posts")
	if err != nil {
		log.Fatalf("blog posts: %s", err)
	}
	posts := make(map[string][]byte, len(postTemplates))
	for _, post := range postTemplates {
		base, err = base.Clone()
		if err != nil {
			log.Fatalf("base.Clone: %s", err)
		}
		postString, err := blogPostFiles.ReadFile("templates/blog/posts/" + post.Name())
		if err != nil {
			log.Fatalf("somehow I fucked the paths up: %s", err)
		}
		postTemplate, err := base.New("post").Parse(string(postString))
		if err != nil {
			log.Fatalf("%q: invalid template: %s", post.Name(), err)
		}
		buf := new(bytes.Buffer)
		if err := postTemplate.ExecuteTemplate(buf, "outline", nil); err != nil {
			log.Fatalf("%q: error: %s", post.Name(), err)
		}
		posts[strings.TrimSuffix(post.Name(), ".html.template")] = buf.Bytes()
	}
	return posts
}

var blogPostsHTML = preloadBlogPosts()

func blog(w http.ResponseWriter, r *http.Request) {
	post, ok := blogPostsHTML[strings.TrimPrefix(r.URL.Path, "/blog/")]
	if !ok {
		notFound(w, r)
		return
	}
	http.ServeContent(w, r, "post.html", serverStartTime, bytes.NewReader(post))
}

//go:embed templates/index.html.template
var indexString string

func preloadIndex() []byte {
	base, err := outlineTemplate.Clone()
	if err != nil {
		log.Fatalf("outlineTemplate.Clone: %s", err)
	}
	base.Funcs(template.FuncMap{
		"name": func(post string) string {
			postBytes, err := blogPostFiles.ReadFile("templates/blog/posts/" + post + ".html.template")
			if err != nil {
				log.Fatalf("no such post %q: %s", post, err)
			}
			date := post[:strings.IndexByte(post, '_')]
			firstLine := postBytes[:bytes.IndexByte(postBytes, '\n')]
			return date + ": " + string(bytes.TrimSuffix(bytes.TrimPrefix(firstLine, []byte("<h1>")), []byte("</h1>")))
		},
	})
	indexTemplate, err := base.New("body").Parse(indexString)
	if err != nil {
		log.Fatalf("index.html.template: invalid template: %s", err)
	}
	posts := make([]string, 0, len(blogPostsHTML))
	for p := range blogPostsHTML {
		posts = append(posts, p)
	}
	slices.Sort(posts)
	buf := new(bytes.Buffer)
	if err := indexTemplate.ExecuteTemplate(buf, "outline", posts); err != nil {
		log.Fatalf("index.html.template: error: %s", err)
	}
	return buf.Bytes()
}

var indexHTML = preloadIndex()

func index(w http.ResponseWriter, r *http.Request) {
	http.ServeContent(w, r, "index.html", serverStartTime, bytes.NewReader(indexHTML))
}

//go:embed templates/pong.html.template
var pongString string

func preloadPong() []byte {
	pongTemplate, err := template.New("pong").Parse(pongString)
	if err != nil {
		log.Fatalf("pong.html.template: invalid template: %s", err)
	}
	buf := new(bytes.Buffer)
	if err := pongTemplate.Execute(buf, nil); err != nil {
		log.Fatalf("pong.html.template: error: %s", err)
	}
	return buf.Bytes()
}

var pongHTML = preloadPong()

func pong(w http.ResponseWriter, r *http.Request) {
	http.ServeContent(w, r, "pong.html", serverStartTime, bytes.NewReader(pongHTML))
}

//go:embed static
var staticFiles embed.FS

func static(w http.ResponseWriter, r *http.Request) {
	fileName := strings.TrimPrefix(r.URL.Path, "/")
	f, err := staticFiles.Open(fileName)
	if err != nil {
		notFound(w, r)
		return
	}
	defer f.Close()
	http.ServeContent(w, r, fileName, serverStartTime, f.(io.ReadSeeker))
}

func main() {
	flag.Parse()

	mux := http.NewServeMux()
	mux.HandleFunc("/blog/", blog)
	mux.HandleFunc("/pong", pong)
	jellyfinURL, err := url.Parse("http://localhost:8096")
	if err != nil {
		log.Fatalf("Jellyfin URL: %s", err)
	}
	mux.Handle("/cinema/", httputil.NewSingleHostReverseProxy(jellyfinURL))
	mux.HandleFunc("/static/", static)
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/" {
			index(w, r)
		} else {
			notFound(w, r)
		}
	})

	httpServer := http.Server{
		Addr:         fmt.Sprintf(":%d", *port),
		Handler:      mux,
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 5 * time.Second,
	}

	log.Printf("Listening on %q", httpServer.Addr)
	if *https {
		log.Fatal(httpServer.ListenAndServeTLS("/var/lib/acme/roseh.moe/cert.pem", "/var/lib/acme/roseh.moe/key.pem"))
	} else {
		log.Fatal(httpServer.ListenAndServe())
	}
}