about summary refs log tree commit diff stats
path: root/internal/server/logging.go
diff options
context:
space:
mode:
authorAlan Pearce2024-05-02 23:18:19 +0200
committerAlan Pearce2024-05-02 23:20:30 +0200
commit73603079e29bc89c54296a9e12b5a779cd84c023 (patch)
tree3e5d0c0c87b81a007667fc4b533cb9403675a422 /internal/server/logging.go
parent7ad48953a4d9470d2f4fe89343c0b09bff410c58 (diff)
downloadsearchix-73603079e29bc89c54296a9e12b5a779cd84c023.tar.lz
searchix-73603079e29bc89c54296a9e12b5a779cd84c023.tar.zst
searchix-73603079e29bc89c54296a9e12b5a779cd84c023.zip
feat: serve a very basic html template
Diffstat (limited to 'internal/server/logging.go')
-rw-r--r--internal/server/logging.go55
1 files changed, 55 insertions, 0 deletions
diff --git a/internal/server/logging.go b/internal/server/logging.go
new file mode 100644
index 0000000..6a16f42
--- /dev/null
+++ b/internal/server/logging.go
@@ -0,0 +1,55 @@
+package server
+
+import (
+	"fmt"
+	"io"
+	"net/http"
+)
+
+type LoggingResponseWriter struct {
+	http.ResponseWriter
+	statusCode int
+}
+
+func (lrw *LoggingResponseWriter) WriteHeader(code int) {
+	lrw.statusCode = code
+	// avoids warning: superfluous response.WriteHeader call
+	if lrw.statusCode != http.StatusOK {
+		lrw.ResponseWriter.WriteHeader(code)
+	}
+}
+
+func NewLoggingResponseWriter(w http.ResponseWriter) *LoggingResponseWriter {
+	return &LoggingResponseWriter{w, http.StatusOK}
+}
+
+type wrappedHandlerOptions struct {
+	defaultHostname string
+	logger          io.Writer
+}
+
+func wrapHandlerWithLogging(wrappedHandler http.Handler, opts wrappedHandlerOptions) http.Handler {
+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		scheme := r.Header.Get("X-Forwarded-Proto")
+		if scheme == "" {
+			scheme = "http"
+		}
+		host := r.Header.Get("Host")
+		if host == "" {
+			host = opts.defaultHostname
+		}
+		lw := NewLoggingResponseWriter(w)
+		wrappedHandler.ServeHTTP(lw, r)
+		statusCode := lw.statusCode
+		fmt.Fprintf(
+			opts.logger,
+			"%s %s %d %s %s %s\n",
+			scheme,
+			r.Method,
+			statusCode,
+			host,
+			r.URL.Path,
+			lw.Header().Get("Location"),
+		)
+	})
+}