From 73603079e29bc89c54296a9e12b5a779cd84c023 Mon Sep 17 00:00:00 2001 From: Alan Pearce Date: Thu, 2 May 2024 23:18:19 +0200 Subject: feat: serve a very basic html template --- internal/server/logging.go | 55 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 internal/server/logging.go (limited to 'internal/server/logging.go') 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"), + ) + }) +} -- cgit 1.4.1