Add middleware to add IP addr from req. to context
This commit is contained in:
29
pkg/api/ipaddr.go
Normal file
29
pkg/api/ipaddr.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Key to use when setting the request ID.
|
||||
type ctxKeyRemoteAddr int
|
||||
|
||||
// RemoteAddrKey is the key that holds th unique request ID in a request context.
|
||||
const remoteAddrKey ctxKeyRemoteAddr = 0
|
||||
|
||||
// Packs remote address to context
|
||||
func remoteAddrToContext(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
next.ServeHTTP(w, req.WithContext(context.WithValue(req.Context(), remoteAddrKey, req.RemoteAddr)))
|
||||
})
|
||||
}
|
||||
|
||||
// RemoteAddrFromContext returns remote IP address from context
|
||||
func RemoteAddrFromContext(ctx context.Context) string {
|
||||
v := ctx.Value(remoteAddrKey)
|
||||
if str, ok := v.(string); ok {
|
||||
return str
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
// contextLogger middleware binds logger to request's context.
|
||||
//
|
||||
// This allows us to use logger from context (with requestID)
|
||||
// inside our (generated) handers and controllers
|
||||
// inside our (generated) handlers and controllers
|
||||
func contextLogger(log *zap.Logger) func(next http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
|
||||
@@ -17,6 +17,7 @@ func BaseMiddleware(log *zap.Logger) []func(http.Handler) http.Handler {
|
||||
return []func(http.Handler) http.Handler{
|
||||
handleCORS,
|
||||
middleware.RealIP,
|
||||
remoteAddrToContext,
|
||||
middleware.RequestID,
|
||||
contextLogger(log),
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user