Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ require (
github.com/go-chi/chi/v5 v5.2.1
github.com/go-chi/render v1.0.3
github.com/golang-cz/devslog v0.0.13
github.com/google/uuid v1.6.0
)

require github.com/ajg/form v1.5.1 // indirect
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,3 @@ github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4=
github.com/go-chi/render v1.0.3/go.mod h1:/gr3hVkmYR0YlEy3LxCuVRFzEu9Ruok+gFqbIofjao0=
github.com/golang-cz/devslog v0.0.13 h1:JkJ6PPNSOCBpYyU03v3xw7WgpChQ3AYFqgRbYBhUk/Y=
github.com/golang-cz/devslog v0.0.13/go.mod h1:bSe5bm0A7Nyfqtijf1OMNgVJHlWEuVSXnkuASiE1vV8=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
32 changes: 4 additions & 28 deletions pkg/api/middlewares.go → pkg/middleware/middleware.go
Original file line number Diff line number Diff line change
@@ -1,47 +1,23 @@
package api
package middleware

import (
"context"
"log/slog"
"net/http"
"time"

"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/google/uuid"
chimiddleware "github.com/go-chi/chi/v5/middleware"
)

type RequestIDContextKey struct{}

func RequestIDMiddleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)

requestID := r.Header.Get("X-Request-ID")
if requestID == "" {
requestID = uuid.New().String()
}

ww.Header().Set("X-Request-ID", requestID)

ctx := r.Context()
ctx = context.WithValue(ctx, RequestIDContextKey{}, requestID)

next.ServeHTTP(ww, r.WithContext(ctx))
})
}
}

func RequestLoggerMiddleware(logger *slog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()

// Create a response writer wrapper to capture status and size
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
ww := chimiddleware.NewWrapResponseWriter(w, r.ProtoMajor)

requestID, ok := r.Context().Value(RequestIDContextKey{}).(string)
requestID, ok := r.Context().Value(chimiddleware.RequestIDKey).(string)
if !ok {
requestID = "unknown"
}
Expand Down