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,6 +3,7 @@ package http
|
|||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Luzifer/go_helpers/accessLogger"
|
||||
|
@ -10,10 +11,14 @@ import (
|
|||
|
||||
type HTTPLogHandler struct {
|
||||
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
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue