logging and middleware chaining
This commit is contained in:
@@ -8,11 +8,14 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
const TraceIdKey contextKey = "trace_id"
|
||||
|
||||
func ContextMiddleware(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) {
|
||||
traceid := uuid.NewString()
|
||||
ctx := context.WithValue(r.Context(), "trace_id", traceid)
|
||||
ctx := context.WithValue(r.Context(), TraceIdKey, traceid)
|
||||
newReq := r.WithContext(ctx)
|
||||
|
||||
next.ServeHTTP(w, newReq)
|
||||
|
||||
19
internal/middleware/util.go
Normal file
19
internal/middleware/util.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
type Middleware func(http.Handler) http.Handler
|
||||
|
||||
func CompileMiddleware(h http.Handler, m []Middleware) http.Handler {
|
||||
if len(m) < 1 {
|
||||
return h
|
||||
}
|
||||
|
||||
wrapped := h
|
||||
|
||||
for i := len(m) - 1; i >= 0; i-- {
|
||||
wrapped = m[i](wrapped)
|
||||
}
|
||||
|
||||
return wrapped
|
||||
}
|
||||
Reference in New Issue
Block a user