2017-04-13 15:05:26 +00:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net/http"
|
2018-04-03 19:51:39 +00:00
|
|
|
"strings"
|
2017-04-13 15:05:26 +00:00
|
|
|
"time"
|
|
|
|
|
2019-02-28 19:15:04 +00:00
|
|
|
"github.com/Luzifer/go_helpers/v2/accessLogger"
|
2017-04-13 15:05:26 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type HTTPLogHandler struct {
|
2018-04-03 19:51:39 +00:00
|
|
|
Handler http.Handler
|
|
|
|
TrustedIPHeaders []string
|
2017-04-13 15:05:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewHTTPLogHandler(h http.Handler) http.Handler {
|
2018-04-03 19:51:39 +00:00
|
|
|
return HTTPLogHandler{
|
|
|
|
Handler: h,
|
|
|
|
TrustedIPHeaders: []string{"X-Forwarded-For", "RemoteAddr", "X-Real-IP"},
|
|
|
|
}
|
2017-04-13 15:05:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (l HTTPLogHandler) ServeHTTP(res http.ResponseWriter, r *http.Request) {
|
|
|
|
start := time.Now()
|
|
|
|
ares := accessLogger.New(res)
|
|
|
|
|
|
|
|
l.Handler.ServeHTTP(ares, r)
|
|
|
|
|
2018-11-18 23:27:55 +00:00
|
|
|
path := r.URL.Path
|
|
|
|
if q := r.URL.Query().Encode(); len(q) > 0 {
|
|
|
|
path = path + "?" + q
|
|
|
|
}
|
|
|
|
|
2017-04-13 15:05:26 +00:00
|
|
|
log.Printf("%s - \"%s %s\" %d %d \"%s\" \"%s\" %s",
|
2018-04-03 19:51:39 +00:00
|
|
|
l.findIP(r),
|
2017-04-13 15:05:26 +00:00
|
|
|
r.Method,
|
2018-11-18 23:27:55 +00:00
|
|
|
path,
|
2017-04-13 15:05:26 +00:00
|
|
|
ares.StatusCode,
|
|
|
|
ares.Size,
|
|
|
|
r.Header.Get("Referer"),
|
|
|
|
r.Header.Get("User-Agent"),
|
|
|
|
time.Since(start),
|
|
|
|
)
|
|
|
|
}
|
2018-04-03 19:51:39 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|