mirror of
https://github.com/Luzifer/go_helpers.git
synced 2024-12-25 05:21:20 +00:00
Add proxy IP detection
Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
parent
8fdddb7041
commit
9f573a19d6
1 changed files with 20 additions and 3 deletions
|
@ -3,17 +3,22 @@ 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"
|
||||||
)
|
)
|
||||||
|
|
||||||
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
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue