about summary refs log tree commit diff stats
path: root/internal/server/error.go
diff options
context:
space:
mode:
authorAlan Pearce2024-05-15 12:44:03 +0200
committerAlan Pearce2024-05-15 12:44:03 +0200
commit2d5ee7b69cbe27e7e1abef7bf3451cb6455c4387 (patch)
treec0d321d6a9f1ea9de1447742175261ed231a3590 /internal/server/error.go
parent149cbe7681607eb48f47df14c7a39e6f289fb7b6 (diff)
downloadsearchix-2d5ee7b69cbe27e7e1abef7bf3451cb6455c4387.tar.lz
searchix-2d5ee7b69cbe27e7e1abef7bf3451cb6455c4387.tar.zst
searchix-2d5ee7b69cbe27e7e1abef7bf3451cb6455c4387.zip
feat: render HTML error pages
Diffstat (limited to 'internal/server/error.go')
-rw-r--r--internal/server/error.go43
1 files changed, 43 insertions, 0 deletions
diff --git a/internal/server/error.go b/internal/server/error.go
new file mode 100644
index 0000000..51453f4
--- /dev/null
+++ b/internal/server/error.go
@@ -0,0 +1,43 @@
+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.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)
+		}
+	}
+}