From c9371d0f6e46bcb80ac770cb56606d4372b2c5fc Mon Sep 17 00:00:00 2001 From: Dmytro Momot Date: Tue, 29 Oct 2024 22:36:45 +0200 Subject: [PATCH] Refactor IpToContext middleware for simplification Replaced nested function and extra type assertion with a more straightforward implementation using http.HandlerFunc. This improves code readability and maintainability while achieving the same functionality of setting the client's IP in the request context. --- middleware.go | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/middleware.go b/middleware.go index 6cfd36f..5d1f013 100644 --- a/middleware.go +++ b/middleware.go @@ -26,14 +26,10 @@ func Middleware(headers ...string) func(http.Handler) http.Handler { // IpToContext is a middleware that sets the client's IP address in the request context. // This IP address can be used in the next handler. -func IpToContext(ctxKey any) func(http.Handler) http.Handler { - return func(h http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - // Get user ip address and set it to the request context - // This ip address can be used in the next handler - h.ServeHTTP(w, r.WithContext(SetIPAddress(r.Context(), r.RemoteAddr))) - } - - return http.HandlerFunc(fn) - } +func IpToContext(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Get user ip address and set it to the request context + // This ip address can be used in the next handler + next.ServeHTTP(w, r.WithContext(SetIPAddress(r.Context(), r.RemoteAddr))) + }) }