2017-05-09 12:02:44 +00:00
|
|
|
package accesslog
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
2017-07-19 10:02:51 +00:00
|
|
|
"github.com/urfave/negroni"
|
2017-05-09 12:02:44 +00:00
|
|
|
"github.com/vulcand/oxy/utils"
|
|
|
|
)
|
|
|
|
|
2018-06-05 07:02:03 +00:00
|
|
|
// SaveBackend sends the backend name to the logger.
|
|
|
|
// These are always used with a corresponding SaveFrontend handler.
|
2017-05-09 12:02:44 +00:00
|
|
|
type SaveBackend struct {
|
|
|
|
next http.Handler
|
|
|
|
backendName string
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewSaveBackend creates a SaveBackend handler.
|
|
|
|
func NewSaveBackend(next http.Handler, backendName string) http.Handler {
|
|
|
|
return &SaveBackend{next, backendName}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (sb *SaveBackend) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
|
2018-06-05 07:02:03 +00:00
|
|
|
serveSaveBackend(rw, r, sb.backendName, func(crw *captureResponseWriter) {
|
|
|
|
sb.next.ServeHTTP(crw, r)
|
|
|
|
})
|
2017-05-09 12:02:44 +00:00
|
|
|
}
|
|
|
|
|
2018-01-11 09:04:03 +00:00
|
|
|
// SaveNegroniBackend sends the backend name to the logger.
|
|
|
|
type SaveNegroniBackend struct {
|
|
|
|
next negroni.Handler
|
|
|
|
backendName string
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewSaveNegroniBackend creates a SaveBackend handler.
|
|
|
|
func NewSaveNegroniBackend(next negroni.Handler, backendName string) negroni.Handler {
|
|
|
|
return &SaveNegroniBackend{next, backendName}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (sb *SaveNegroniBackend) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
|
2018-06-05 07:02:03 +00:00
|
|
|
serveSaveBackend(rw, r, sb.backendName, func(crw *captureResponseWriter) {
|
|
|
|
sb.next.ServeHTTP(crw, r, next)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func serveSaveBackend(rw http.ResponseWriter, r *http.Request, backendName string, apply func(*captureResponseWriter)) {
|
2018-01-11 09:04:03 +00:00
|
|
|
table := GetLogDataTable(r)
|
2018-06-05 07:02:03 +00:00
|
|
|
table.Core[BackendName] = backendName
|
|
|
|
table.Core[BackendURL] = r.URL // note that this is *not* the original incoming URL
|
|
|
|
table.Core[BackendAddr] = r.URL.Host
|
2018-01-11 09:04:03 +00:00
|
|
|
|
|
|
|
crw := &captureResponseWriter{rw: rw}
|
|
|
|
start := time.Now().UTC()
|
|
|
|
|
2018-06-05 07:02:03 +00:00
|
|
|
apply(crw)
|
2018-01-11 09:04:03 +00:00
|
|
|
|
|
|
|
// use UTC to handle switchover of daylight saving correctly
|
|
|
|
table.Core[OriginDuration] = time.Now().UTC().Sub(start)
|
|
|
|
table.Core[OriginStatus] = crw.Status()
|
|
|
|
// make copy of headers so we can ensure there is no subsequent mutation during response processing
|
|
|
|
table.OriginResponse = make(http.Header)
|
|
|
|
utils.CopyHeaders(table.OriginResponse, crw.Header())
|
|
|
|
table.Core[OriginContentSize] = crw.Size()
|
|
|
|
}
|