Commit 6337ade7735b01ceeb85bd6af2f70d654bc09d08

Parents: e794dabb988b321a0c99a378eb1469e9681b6ede

From: Moritz Poldrack <git@moritz.sh>
Date: Mon Nov 20 15:20:22 2023 +0700

log: log response status

		

Stats

internal/conman/conman.go +20/-2
internal/handler/404.go +1/-0
internal/handler/serve-http.go +3/-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
71
72
diff --git a/internal/conman/conman.go b/internal/conman/conman.go
index 28d35eab21e0833c4327f40fb698e970c2371d71..4fe356ebe5acf91c3ac2e180777f1f2c57b06abb 100644
--- a/internal/conman/conman.go
+++ b/internal/conman/conman.go
@@ -8,8 +8,12 @@ )
 
 type contextKey uint8
 
-// Logger is a context key for the logger.
-const Logger contextKey = iota + 1
+const (
+	// Logger is a context key for the logger.
+	Logger contextKey = iota
+	// Status is a context key for the response status.
+	Status contextKey = iota
+)
 
 // StoreLogger stores a logger in the context.
 func StoreLogger(ctx *fasthttp.RequestCtx, value *slog.Logger) {
@@ -24,3 +28,17 @@ 		return slog.Default().With("error", "context retrieval failed")
 	}
 	return v.(*slog.Logger)
 }
+
+// StoreStatus stores a status in the context.
+func StoreStatus(ctx *fasthttp.RequestCtx, value int) {
+	ctx.SetUserValue(Logger, value)
+}
+
+// GetStatus retrieves a status from the context.
+func GetStatus(ctx *fasthttp.RequestCtx) int {
+	v := ctx.Value(Status)
+	if v == nil {
+		return 0
+	}
+	return v.(int)
+}
diff --git a/internal/handler/404.go b/internal/handler/404.go
index 640941000b99dc7dd63230b85cc13ce2d8a4d750..7bdf042e54bf084c2a39303fb8cf6dd22916e14b 100644
--- a/internal/handler/404.go
+++ b/internal/handler/404.go
@@ -23,6 +23,7 @@ 	default:
 		log.Error("internal server error", "error", err.Error())
 	}
 	ctx.SetStatusCode(status)
+	conman.StoreStatus(ctx, status)
 
 	_, _ = fmt.Fprintf(ctx, "error: %v", err)
 }
diff --git a/internal/handler/serve-http.go b/internal/handler/serve-http.go
index 56160f17f62b6c0b60fa3890b410865544847ef8..0e3151d2e9baa36aba0a86a957ae64f06d0d897e 100644
--- a/internal/handler/serve-http.go
+++ b/internal/handler/serve-http.go
@@ -17,8 +17,9 @@ func (h *Handler) Serve(ctx *fasthttp.RequestCtx) {
 	start := time.Now()
 	log := slog.With("requestID", h.requestID.Add(1))
 	defer func() {
-		log.Debug("request completed", "duration", time.Since(start))
+		log.Debug("request completed", "duration", time.Since(start), "status", conman.GetStatus(ctx))
 	}()
+	conman.StoreStatus(ctx, fasthttp.StatusOK)
 	log.Info(
 		"incoming request",
 		"method", ctx.Method(),
@@ -52,6 +53,7 @@ 	}
 
 	if bytes.Equal(ctx.Path(), []byte("/favicon.ico")) {
 		ctx.SetStatusCode(fasthttp.StatusNoContent)
+		conman.StoreStatus(ctx, fasthttp.StatusNoContent)
 		return
 	}