chiclientip/client_ip.go

29 lines
852 B
Go
Raw Normal View History

2023-05-12 04:54:44 +00:00
package chiclientip
import (
"context"
"net/http"
"github.com/realclientip/realclientip-go"
)
type clientIPCtxKey struct{}
// ClientIP is a go-chi middleware that derives the client IP from realclientip.Strategy
// and stores it in the http.Request Context.
func ClientIP(strat realclientip.Strategy) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
clientIP := strat.ClientIP(r.Header, r.RemoteAddr)
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey{}, clientIP))
next.ServeHTTP(w, r)
})
}
}
// ClientIPFromContext returns the client ip in context.Context if exists.
func ClientIPFromContext(ctx context.Context) (string, bool) {
clientIP, ok := ctx.Value(clientIPCtxKey{}).(string)
return clientIP, ok
}