1
0
Fork 0
mirror of https://github.com/Luzifer/go_helpers.git synced 2024-12-24 13:01: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,17 +3,22 @@ package http
import (
"log"
"net/http"
"strings"
"time"
"github.com/Luzifer/go_helpers/accessLogger"
)
type HTTPLogHandler struct {
Handler http.Handler
Handler http.Handler
TrustedIPHeaders []string
}
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) {
@ -23,7 +28,7 @@ func (l HTTPLogHandler) ServeHTTP(res http.ResponseWriter, r *http.Request) {
l.Handler.ServeHTTP(ares, r)
log.Printf("%s - \"%s %s\" %d %d \"%s\" \"%s\" %s",
r.RemoteAddr,
l.findIP(r),
r.Method,
r.URL.Path,
ares.StatusCode,
@ -33,3 +38,15 @@ func (l HTTPLogHandler) ServeHTTP(res http.ResponseWriter, r *http.Request) {
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
}