Log all HTTP requests when running with -debug

This commit is contained in:
2021-07-12 15:50:04 +02:00
parent b6a17117dd
commit 097352e181
2 changed files with 48 additions and 2 deletions

View File

@@ -0,0 +1,43 @@
package httpserver
import (
"encoding/base64"
"net/http"
"strings"
auth "github.com/abbot/go-http-auth"
"github.com/sirupsen/logrus"
)
// LoggingWrap wraps a HTTP Handler and logs all requests to the Debug log level.
// This is intended as a debugging tool only.
func LoggingWrap(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
logger := logrus.WithFields(logrus.Fields{
"uri": r.URL.String(),
"method": r.Method,
"remote_addr": r.RemoteAddr,
"username": getAuthUsername(r),
})
logger.Debug("incoming HTTP request")
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func getAuthUsername(r *http.Request) string {
s := strings.SplitN(r.Header.Get(auth.NormalHeaders.Authorization), " ", 2)
if len(s) != 2 || s[0] != "Basic" {
return ""
}
b, err := base64.StdEncoding.DecodeString(s[1])
if err != nil {
return ""
}
pair := strings.SplitN(string(b), ":", 2)
if len(pair) != 2 {
return ""
}
return pair[0]
}