git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/httpx/middlewarex/set_logger.go (about)

     1  package middlewarex
     2  
     3  import (
     4  	"log/slog"
     5  	"net/http"
     6  
     7  	"git.sr.ht/~pingoo/stdx/log/slogx"
     8  	"git.sr.ht/~pingoo/stdx/ulid"
     9  )
    10  
    11  // SetLogger injects `logger` in the context of requests
    12  func SetLogger(logger *slog.Logger) func(next http.Handler) http.Handler {
    13  	return func(next http.Handler) http.Handler {
    14  		fn := func(w http.ResponseWriter, req *http.Request) {
    15  			ctx := req.Context()
    16  			routeLogger := logger.With(
    17  				slog.Group("http", slog.String("method", req.Method), slog.String("path", req.URL.Path)),
    18  			)
    19  
    20  			reqIDContextValue := ctx.Value(RequestIDCtxKey)
    21  			if requestID, ok := reqIDContextValue.(ulid.ULID); ok {
    22  				routeLogger = routeLogger.With(slog.String("request_id", requestID.String()))
    23  			}
    24  
    25  			ctx = slogx.ToCtx(ctx, routeLogger)
    26  			req = req.WithContext(ctx)
    27  
    28  			next.ServeHTTP(w, req)
    29  		}
    30  		return http.HandlerFunc(fn)
    31  	}
    32  }