middleware/real_ip.go

55 lines
1.6 KiB
Go
Raw Normal View History

2020-11-07 11:59:33 +00:00
package middleware
import (
2022-05-12 11:29:33 +00:00
"context"
2020-11-07 11:59:33 +00:00
"net/http"
"strings"
)
2022-05-12 11:29:33 +00:00
var (
RealIPCtxKey = &CtxKey{Pkg: "go.pkg.cx/middleware", Name: "RealIP"}
)
2020-11-07 11:59:33 +00:00
// RealIP is a middleware that sets a http.Request's RemoteAddr to the results
// of parsing either the X-Forwarded-For header or the X-Real-IP header (in that
// order).
//
// This middleware should be inserted fairly early in the middleware stack to
// ensure that subsequent layers (e.g., request loggers) which examine the
// RemoteAddr will see the intended value.
//
// You should only use this middleware if you can trust the headers passed to
// you (in particular, the two headers this middleware uses), for example
// because you have placed a reverse proxy like HAProxy or nginx in front of
// chi. If your reverse proxies are configured to pass along arbitrary header
// values from the client, or if you use this middleware without a reverse
// proxy, malicious clients will be able to make you very sad (or, depending on
// how you're using RemoteAddr, vulnerable to an attack of some sort).
func RealIP(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if rip := realIP(r); rip != "" {
r.RemoteAddr = rip
}
2022-05-12 11:29:33 +00:00
ctx := context.WithValue(r.Context(), RealIPCtxKey, strings.Split(r.RemoteAddr, ":")[0])
next.ServeHTTP(w, r.WithContext(ctx))
2020-11-07 11:59:33 +00:00
})
}
func realIP(r *http.Request) string {
if xrip := r.Header.Get("X-Real-IP"); xrip != "" {
return xrip
}
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
i := strings.Index(xff, ", ")
if i == -1 {
i = len(xff)
}
return xff[:i]
}
return ""
}