chiclientip/client_ip.go

29 lines
858 B
Go

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(strategy 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 := strategy.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
}