about summary refs log tree commit diff stats
path: root/internal/server/error.go
blob: 6994ad7b0435cdbe9f22e8007d8c13ddaa386f49 (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
package server

import (
	"log/slog"
	"net/http"
	"searchix/internal/config"
)

func createErrorHandler(
	config *config.Config,
) func(http.ResponseWriter, *http.Request, string, int) {
	return func(w http.ResponseWriter, r *http.Request, message string, code int) {
		var err error
		if message == "" {
			message = http.StatusText(code)
		}
		indexData := TemplateData{
			ExtraHeadHTML: config.Web.ExtraHeadHTML,
			Sources:       config.Importer.Sources,
			Version:       *versionInfo,
			Code:          code,
			Message:       message,
		}
		w.Header().Set("Cache-Control", "no-store")
		w.Header().Del("Vary")
		w.WriteHeader(code)
		if r.Header.Get("Fetch") == "true" {
			err = templates["error"].ExecuteTemplate(w, "main", indexData)
		} else {
			err = templates["error"].Execute(w, indexData)
		}
		if err != nil {
			slog.Error(
				"error rendering error page template",
				"error",
				err,
				"code",
				code,
				"message",
				message,
			)
			http.Error(w, message, code)
		}
	}
}