Skip to content

Commit

Permalink
Refactor IpToContext middleware for simplification
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
dmitrymomot committed Oct 29, 2024
1 parent edddaa8 commit c9371d0
Showing 1 changed file with 6 additions and 10 deletions.
16 changes: 6 additions & 10 deletions middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
})
}

0 comments on commit c9371d0

Please sign in to comment.