Skip to content

Commit

Permalink
Added middleware to set IP address to request context + helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
dmitrymomot committed Oct 29, 2024
1 parent be2ae3d commit edddaa8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
26 changes: 26 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package clientip

import "context"

// contextKey is a type used for keys in the context.
// These keys are used to store and retrieve values from the context.
// The keys are unique and are used to avoid conflicts with other keys.
type contextKey struct{ name string }

// requestIPKey is the key used to store the client's IP address in the request context.
var requestIPKey = contextKey{"request_ip"}

// SetIPAddress sets the client's IP address in the request context.
// This IP address can be used in the next handler.
func SetIPAddress(ctx context.Context, ip string) context.Context {
return context.WithValue(ctx, requestIPKey, ip)
}

// GetIPAddress gets the client's IP address from the request context.
// If the IP address is not found in the context, it returns an empty string.
func GetIPAddress(ctx context.Context) string {
if ip, ok := ctx.Value(requestIPKey).(string); ok {
return ip
}
return ""
}
14 changes: 14 additions & 0 deletions middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,17 @@ func Middleware(headers ...string) func(http.Handler) http.Handler {
return http.HandlerFunc(fn)
}
}

// 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)
}
}

0 comments on commit edddaa8

Please sign in to comment.