numerus/pkg/logger/middleware.go
jordi fita mas 9d202e82ca Add the simplest possible web server to test login
This is a very rough test to actually check the login function outside
pgTAP; it is very ugly, in both design and code, and (i hope) does not
reflect future quality.

I was about to use Echo[0] as a “web framework”, but something feels
wrong when using a framework with Go—i do not know what.  I actually
tried it and was even more put off by the JSON-formatted logger that can
not be disabled; i was already losing control of the application!

I created the folder following the apparently de facto guidelines for Go
projects, and i see no problem with mixing Go’s folders with Sqitch’s:
both are part of the same application and there are not conflicts.

[0]: https://echo.labstack.com/
[1]: https://github.com/golang-standards/project-layout
2023-01-13 20:53:43 +01:00

61 lines
1.1 KiB
Go

package logger
import (
"log"
"net/http"
"time"
)
type loggerResponseWriter struct {
http.ResponseWriter
statusCode int
responseSize int
}
func (w *loggerResponseWriter) WriteHeader(statusCode int) {
w.statusCode = statusCode
w.ResponseWriter.WriteHeader(statusCode)
}
func (w *loggerResponseWriter) Write(b []byte) (int, error) {
w.responseSize += len(b)
return w.ResponseWriter.Write(b)
}
func (w *loggerResponseWriter) Flush() {
if f, ok := w.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}
func Logger(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t := time.Now()
logger := loggerResponseWriter{w, 0, 0}
handler.ServeHTTP(&logger, r)
statusCode := logger.statusCode
if statusCode == 0 {
statusCode = http.StatusOK
}
referer := r.Referer()
if referer == "" {
referer = "-"
}
log.Printf("HTTP - %s - - [%s] \"%s %s %s\" %d %d \"%s\" \"%s\" %s\n",
r.RemoteAddr,
t.Format("02/Jan/2006:15:04:05 -0700"),
r.Method,
r.URL.Path,
r.Proto,
statusCode,
logger.responseSize,
referer,
r.UserAgent(),
time.Since(t),
)
})
}