about summary refs log tree commit diff stats
path: root/cmd/server/server.go
blob: 9c9911a5e26d35ad8bcdaf0a322bed8d1d151dbb (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
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package main

import (
	"fmt"
	"hash/fnv"
	"io"
	"io/fs"
	"log"
	"log/slog"
	"mime"
	"net"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"

	cfg "website/internal/config"

	"github.com/ardanlabs/conf/v3"
	"github.com/getsentry/sentry-go"
	sentryhttp "github.com/getsentry/sentry-go/http"
	"github.com/pkg/errors"
	"github.com/shengyanli1982/law"
)

type Config struct {
	Production             bool    `conf:"default:false"`
	ListenAddress          string  `conf:"default:localhost"`
	Port                   uint16  `conf:"default:3000,short:p"`
	BaseURL                cfg.URL `conf:"default:http://localhost:3000,short:b"`
	RedirectOtherHostnames bool    `conf:"default:false"`
}

var Commit string

var config *cfg.Config

type File struct {
	filename string
	etag     string
}

var files = map[string]File{}

func hashFile(filename string) (string, error) {
	f, err := os.Open(filename)
	if err != nil {
		return "", err
	}
	defer f.Close()
	hash := fnv.New64a()
	if _, err := io.Copy(hash, f); err != nil {
		return "", err
	}
	return fmt.Sprintf(`W/"%x"`, hash.Sum(nil)), nil
}

func registerFile(urlpath string, filepath string) error {
	if files[urlpath] != (File{}) {
		log.Printf("registerFile called with duplicate file, urlPath: %s", urlpath)
		return nil
	}
	hash, err := hashFile(filepath)
	if err != nil {
		return err
	}
	files[urlpath] = File{
		filename: filepath,
		etag:     hash,
	}
	return nil
}

func registerContentFiles(root string) error {
	err := filepath.WalkDir(root, func(filePath string, f fs.DirEntry, err error) error {
		if err != nil {
			return errors.WithMessagef(err, "failed to access path %s", filePath)
		}
		relPath, err := filepath.Rel(root, filePath)
		if err != nil {
			return errors.WithMessagef(err, "failed to make path relative, path: %s", filePath)
		}
		urlPath, _ := strings.CutSuffix(relPath, "index.html")
		if !f.IsDir() {
			slog.Debug("registering file", "urlpath", "/"+urlPath)
			return registerFile("/"+urlPath, filePath)
		}
		return nil
	})
	if err != nil {
		return err
	}
	return nil
}

type HTTPError struct {
	Error   error
	Message string
	Code    int
}

func canonicalisePath(path string) (cPath string, differs bool) {
	cPath = path
	if strings.HasSuffix(path, "/index.html") {
		cPath, differs = strings.CutSuffix(path, "index.html")
	} else if !strings.HasSuffix(path, "/") && files[path+"/"] != (File{}) {
		cPath, differs = path+"/", true
	}
	return cPath, differs
}

func serveFile(w http.ResponseWriter, r *http.Request) *HTTPError {
	urlPath, shouldRedirect := canonicalisePath(r.URL.Path)
	if shouldRedirect {
		http.Redirect(w, r, urlPath, 302)
		return nil
	}
	file := files[urlPath]
	if file == (File{}) {
		return &HTTPError{
			Message: "File not found",
			Code:    http.StatusNotFound,
		}
	}
	w.Header().Add("ETag", file.etag)
	w.Header().Add("Vary", "Accept-Encoding")
	for k, v := range config.Extra.Headers {
		w.Header().Add(k, v)
	}

	http.ServeFile(w, r, files[urlPath].filename)
	return nil
}

type webHandler func(http.ResponseWriter, *http.Request) *HTTPError

func (fn webHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	defer func() {
		if fail := recover(); fail != nil {
			w.WriteHeader(http.StatusInternalServerError)
			slog.Error("runtime panic!", "error", fail)
		}
	}()
	w.Header().Set("Server", fmt.Sprintf("website (%s)", Commit))
	if err := fn(w, r); err != nil {
		if strings.Contains(r.Header.Get("Accept"), "text/html") {
			w.WriteHeader(err.Code)
			notFoundPage := "website/private/404.html"
			http.ServeFile(w, r, notFoundPage)
		} else {
			http.Error(w, err.Message, err.Code)
		}
	}
}

var newMIMEs = map[string]string{
	".xsl": "text/xsl",
}

func fixupMIMETypes() {
	for ext, newType := range newMIMEs {
		if err := mime.AddExtensionType(ext, newType); err != nil {
			slog.Error("could not update mime type", "ext", ext, "mime", newType)
		}
	}
}

type loggingResponseWriter struct {
	http.ResponseWriter
	statusCode int
}

func (lrw *loggingResponseWriter) WriteHeader(code int) {
	lrw.statusCode = code
	// avoids warning: superfluous response.WriteHeader call
	if lrw.statusCode != http.StatusOK {
		lrw.ResponseWriter.WriteHeader(code)
	}
}

func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
	return &loggingResponseWriter{w, http.StatusOK}
}

type wrappedHandlerOptions struct {
	defaultHostname string
	logger          io.Writer
}

func wrapHandlerWithLogging(wrappedHandler http.Handler, opts wrappedHandlerOptions) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		scheme := r.Header.Get("X-Forwarded-Proto")
		if scheme == "" {
			scheme = "http"
		}
		host := r.Header.Get("Host")
		if host == "" {
			host = opts.defaultHostname
		}
		lw := NewLoggingResponseWriter(w)
		wrappedHandler.ServeHTTP(lw, r)
		statusCode := lw.statusCode
		fmt.Fprintf(
			opts.logger,
			"%s %s %d %s %s %s\n",
			scheme,
			r.Method,
			statusCode,
			host,
			r.URL.Path,
			lw.Header().Get("Location"),
		)
	})
}

func main() {
	if os.Getenv("DEBUG") != "" {
		slog.SetLogLoggerLevel(slog.LevelDebug)
	}

	fixupMIMETypes()

	runtimeConfig := Config{}
	help, err := conf.Parse("", &runtimeConfig)
	if err != nil {
		if errors.Is(err, conf.ErrHelpWanted) {
			fmt.Println(help)
			os.Exit(1)
		}
		log.Panicf("parsing runtime configuration: %v", err)
	}

	config, err = cfg.GetConfig()
	if err != nil {
		log.Panicf("parsing configuration file: %v", err)
	}

	cwd, err := os.Getwd()
	if err != nil {
		log.Panicf("don't know where I am")
	}
	slog.Debug("starting at", "wd", cwd)

	prefix := "website/public"
	slog.Debug("registering content files", "prefix", prefix)
	err = registerContentFiles(prefix)
	if err != nil {
		log.Panicf("registering content files: %v", err)
	}

	env := "development"
	if runtimeConfig.Production {
		env = "production"
	}
	err = sentry.Init(sentry.ClientOptions{
		EnableTracing:    true,
		TracesSampleRate: 1.0,
		Dsn:              os.Getenv("SENTRY_DSN"),
		Release:          Commit,
		Environment:      env,
	})
	if err != nil {
		log.Panic("could not set up sentry")
	}
	defer sentry.Flush(2 * time.Second)
	sentryHandler := sentryhttp.New(sentryhttp.Options{
		Repanic: true,
	})

	mux := http.NewServeMux()
	slog.Debug("binding main handler to", "host", runtimeConfig.BaseURL.Hostname()+"/")
	mux.Handle(runtimeConfig.BaseURL.Hostname()+"/", webHandler(serveFile))

	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		newURL := runtimeConfig.BaseURL.String() + r.URL.String()
		http.Redirect(w, r, newURL, 301)
	})

	var logWriter io.Writer
	if runtimeConfig.Production {
		logWriter = law.NewWriteAsyncer(os.Stdout, nil)
	} else {
		logWriter = os.Stdout
	}
	http.Handle("/",
		sentryHandler.Handle(
			wrapHandlerWithLogging(mux, wrappedHandlerOptions{
				defaultHostname: runtimeConfig.BaseURL.Hostname(),
				logger:          logWriter,
			}),
		),
	)
	// no logging, no sentry
	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	listenAddress := net.JoinHostPort(runtimeConfig.ListenAddress, fmt.Sprint(runtimeConfig.Port))
	log.Fatal(http.ListenAndServe(listenAddress, nil))
}