centrifugal / centrifuge

Real-time messaging library for Go. The simplest way to add feature-rich and scalable WebSocket support to your application. The core of Centrifugo server.

Home Page:https://pkg.go.dev/github.com/centrifugal/centrifuge

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

how to get the client ip?

make3782 opened this issue · comments

how to get the client ip? i can't find any method to get the client ip, tks.

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))
	})
}

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