how to get the client ip?
make3782 opened this issue · comments
小暄子 commented
how to get the client ip? i can't find any method to get the client ip, tks.
Alexander Emelin commented
Hello, you can put client IP into context inside middleware and retrieve it later.
func getIP(r *http.Request) string {
...
}
type ipKey struct{}
func ipMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := getIP(r)
newCtx := context.WithValue(r.Context(), ipKey{}, ip)
h.ServeHTTP(w, r.WithContext(newCtx))
})
}
小暄子 commented
Hello, you can put client IP into context inside middleware and retrieve it later.
func getIP(r *http.Request) string { ... } type ipKey struct{} func ipMiddleware(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ip := getIP(r) newCtx := context.WithValue(r.Context(), ipKey{}, ip) h.ServeHTTP(w, r.WithContext(newCtx)) }) }
tks