3
0

Add middleware to add IP addr from req. to context

This commit is contained in:
Denis Arh
2020-05-11 16:07:41 +02:00
parent b1a7425ddc
commit 9613bb7c85
3 changed files with 31 additions and 1 deletions

29
pkg/api/ipaddr.go Normal file
View 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 ""
}

View File

@@ -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) {

View File

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