29 lines
852 B
Go
29 lines
852 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(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
|
||
|
}
|