diff --git a/httpserver/requestlogger.go b/httpserver/requestlogger.go new file mode 100644 index 00000000..d680b63e --- /dev/null +++ b/httpserver/requestlogger.go @@ -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] +} diff --git a/main.go b/main.go index 7382313d..a7639eb1 100644 --- a/main.go +++ b/main.go @@ -24,6 +24,7 @@ package main import ( "fmt" + "net/http" "os" "os/signal" "strings" @@ -36,7 +37,6 @@ import ( "github.com/armadillica/flamenco-manager/jwtauth" "github.com/armadillica/flamenco-manager/shaman" "github.com/armadillica/flamenco-manager/websetup" - "github.com/gorilla/mux" ) var applicationVersion = "set-during-build" @@ -114,7 +114,7 @@ func main() { } showFlamencoServerURL() - var router *mux.Router + var router http.Handler var setup *websetup.Routes if cliArgs.setup { setup, router, err = setupMode() @@ -131,6 +131,9 @@ func main() { // Create the HTTP server before allowing the shutdown signal Handler // to exist. This prevents a race condition when Ctrl+C is pressed after // the http.Server is created, but before it is assigned to httpServer. + if cliArgs.debug { + router = httpserver.LoggingWrap(router) + } httpServer = httpserver.New(config, router) shutdownComplete = make(chan struct{})