Commit 2d28d9e0fdd137d164a0ef6db38b9d0be3d36123

Parents: 33a08c64bf86bbc9dfdba25fd167fc77f64e4a53

From: Moritz Poldrack <git@moritz.sh>
Date: Sat Nov 4 17:40:22 2023 +0700

server: replace 404 handler with more flexible error handler

		

Stats

internal/handler/404.go +16/-4
internal/handler/repo.go +2/-0
internal/handler/serve-http.go +9/-1

Changeset

 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
diff --git a/internal/handler/404.go b/internal/handler/404.go
index 87ab544859144e7f78525cdc1f737ace675a7d8b..dd387f7bc07a44578fac69876145d2833bd240f5 100644
--- a/internal/handler/404.go
+++ b/internal/handler/404.go
@@ -1,9 +1,21 @@
 package handler
 
-import "net/http"
+import (
+	"errors"
+	"fmt"
 
-func handle404(w http.ResponseWriter, r *http.Request) {
-	w.WriteHeader(http.StatusNotFound)
+	"github.com/valyala/fasthttp"
+)
 
-	_, _ = w.Write([]byte("page not found"))
+func errorHandler(ctx *fasthttp.RequestCtx, err error) {
+	status := fasthttp.StatusInternalServerError
+	switch {
+	case errors.Is(err, ErrNotFound):
+		status = fasthttp.StatusNotFound
+	}
+	ctx.SetStatusCode(status)
+
+	_, _ = fmt.Fprintf(ctx, "error: %v", err)
 }
+
+var ErrNotFound = errors.New("page not found")
diff --git a/internal/handler/repo.go b/internal/handler/repo.go
index 564bdd404cc852f4f2c11e30d1658ed480676a27..16f49ce131fa683b57168ca0582fc453b948ebe3 100644
--- a/internal/handler/repo.go
+++ b/internal/handler/repo.go
@@ -19,5 +19,7 @@ 	case "":
 		templates.Overview(repo)(ctx)
 	case "commit":
 		commitHandler(repo)(ctx)
+	default:
+		errorHandler(ctx, ErrNotFound)
 	}
 }
diff --git a/internal/handler/serve-http.go b/internal/handler/serve-http.go
index f92c0ff37fbc203c1fbb0a1ba5df2e94744d2220..8160e47d7a0da94ea61afb6d6daf5ebfca4e3947 100644
--- a/internal/handler/serve-http.go
+++ b/internal/handler/serve-http.go
@@ -12,7 +12,14 @@ )
 
 func (h *Handler) Serve(ctx *fasthttp.RequestCtx) {
 	log := slog.With("requestID", h.requestID.Add(1))
-	log.Info("incoming request", "method", ctx.Method(), "server", ctx.Host(), "path", ctx.Path(), "remoteAddr", ctx.RemoteAddr())
+	log.Info(
+		"incoming request",
+		"method", ctx.Method(),
+		"server", ctx.Host(),
+		"path", ctx.Path(),
+		"remoteAddr", ctx.RemoteAddr(),
+		"user_agent", string(ctx.Request.Header.Peek("User-Agent")),
+	)
 	conman.StoreLogger(ctx, log)
 
 	if string(ctx.Path()) == "/" {
@@ -25,6 +32,7 @@ 	}
 
 	repo := h.lookupProject(string(ctx.Path()))
 	if repo == nil {
+		errorHandler(ctx, ErrNotFound)
 		return
 	}
 	h.repoHandler(ctx, repo)