1
0
Fork 0
mirror of https://github.com/Luzifer/go_helpers.git synced 2024-12-25 13:31:21 +00:00

Add proxy IP detection

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2018-04-03 21:51:39 +02:00
parent 8fdddb7041
commit 9f573a19d6
Signed by: luzifer
GPG key ID: DC2729FDD34BE99E

View file

@ -3,6 +3,7 @@ package http
import ( import (
"log" "log"
"net/http" "net/http"
"strings"
"time" "time"
"github.com/Luzifer/go_helpers/accessLogger" "github.com/Luzifer/go_helpers/accessLogger"
@ -10,10 +11,14 @@ import (
type HTTPLogHandler struct { type HTTPLogHandler struct {
Handler http.Handler Handler http.Handler
TrustedIPHeaders []string
} }
func NewHTTPLogHandler(h http.Handler) http.Handler { func NewHTTPLogHandler(h http.Handler) http.Handler {
return HTTPLogHandler{Handler: h} return HTTPLogHandler{
Handler: h,
TrustedIPHeaders: []string{"X-Forwarded-For", "RemoteAddr", "X-Real-IP"},
}
} }
func (l HTTPLogHandler) ServeHTTP(res http.ResponseWriter, r *http.Request) { func (l HTTPLogHandler) ServeHTTP(res http.ResponseWriter, r *http.Request) {
@ -23,7 +28,7 @@ func (l HTTPLogHandler) ServeHTTP(res http.ResponseWriter, r *http.Request) {
l.Handler.ServeHTTP(ares, r) l.Handler.ServeHTTP(ares, r)
log.Printf("%s - \"%s %s\" %d %d \"%s\" \"%s\" %s", log.Printf("%s - \"%s %s\" %d %d \"%s\" \"%s\" %s",
r.RemoteAddr, l.findIP(r),
r.Method, r.Method,
r.URL.Path, r.URL.Path,
ares.StatusCode, ares.StatusCode,
@ -33,3 +38,15 @@ func (l HTTPLogHandler) ServeHTTP(res http.ResponseWriter, r *http.Request) {
time.Since(start), time.Since(start),
) )
} }
func (l HTTPLogHandler) findIP(r *http.Request) string {
remoteAddr := strings.SplitN(r.RemoteAddr, ":", 2)[0]
for _, hdr := range l.TrustedIPHeaders {
if value := r.Header.Get(hdr); value != "" {
return strings.SplitN(value, ",", 2)[0]
}
}
return remoteAddr
}