chiclientip/client_ip.go

29 lines
858 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.
2023-05-12 04:56:51 +00:00
func ClientIP(strategy realclientip.Strategy) func(next http.Handler) http.Handler {
2023-05-12 04:54:44 +00:00
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2023-05-12 04:56:51 +00:00
clientIP := strategy.ClientIP(r.Header, r.RemoteAddr)
2023-05-12 04:54:44 +00:00
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
}