summaryrefslogtreecommitdiff
path: root/server/middleware
diff options
context:
space:
mode:
Diffstat (limited to 'server/middleware')
-rw-r--r--server/middleware/logging.go50
1 files changed, 50 insertions, 0 deletions
diff --git a/server/middleware/logging.go b/server/middleware/logging.go
new file mode 100644
index 0000000..860a467
--- /dev/null
+++ b/server/middleware/logging.go
@@ -0,0 +1,50 @@
+package middleware
+
+import (
+ "bytes"
+ "log"
+ "net/http"
+ "time"
+)
+
+type LoggingResponseWriter struct {
+ http.ResponseWriter
+ statusCode int
+ responseBody *bytes.Buffer
+}
+
+func (w *LoggingResponseWriter) WriteHeader(code int) {
+ w.statusCode = code
+ w.ResponseWriter.WriteHeader(code)
+}
+
+func (w *LoggingResponseWriter) Write(data []byte) (int, error) {
+ w.responseBody.Write(data)
+ return w.ResponseWriter.Write(data)
+}
+
+func LoggingMiddleware(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ start := time.Now()
+
+ loggingWriter := &LoggingResponseWriter{
+ ResponseWriter: w,
+ statusCode: http.StatusOK,
+ responseBody: &bytes.Buffer{},
+ }
+
+ next.ServeHTTP(loggingWriter, r)
+
+ log.Printf(
+ "Client IP: %s | Method: %s | Path: %s | Status: %d | Duration: %v",
+ r.RemoteAddr,
+ r.Method,
+ r.URL.Path,
+ loggingWriter.statusCode,
+ time.Since(start),
+ )
+ if loggingWriter.responseBody.Len() > 0 {
+ log.Print(loggingWriter.responseBody.String())
+ }
+ })
+}