diff --git a/cmd/server/main.go b/cmd/server/main.go index 13bd2cc..f398b78 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -21,8 +21,8 @@ func main() { router := http.NewServeMux() notesRouter := views.GetRoutes("/notes") - router.Handle("/", http.RedirectHandler("/notes/", http.StatusFound)) - router.Handle("/notes/", http.StripPrefix("/notes", notesRouter)) + router.Handle("/", logger(http.RedirectHandler("/notes/", http.StatusFound))) + router.Handle("/notes/", logger(http.StripPrefix("/notes", notesRouter))) router.Handle( "/static/", logger( @@ -37,9 +37,27 @@ func main() { log.Fatal(http.Serve(listener, router)) } +type loggingResponseWriter struct { + http.ResponseWriter + statusCode int +} + +func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter { + return &loggingResponseWriter{w, http.StatusOK} +} + +func (w *loggingResponseWriter) WriteHeader(code int) { + w.statusCode = code + w.ResponseWriter.WriteHeader(code) +} + func logger(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - log.Print(r.URL.Path) - next.ServeHTTP(w, r) + lwr := NewLoggingResponseWriter(w) + next.ServeHTTP(lwr, r) + + if conf.Conf.LogAccess { + log.Printf("%s %s %s%s %d", r.RemoteAddr, r.Method, r.Host, r.URL.Path, lwr.statusCode) + } }) } diff --git a/conf.example.toml b/conf.example.toml index 99899e3..a606f72 100644 --- a/conf.example.toml +++ b/conf.example.toml @@ -2,3 +2,4 @@ extension = "md" notesdir = "/var/lib/gonotes/saved_notes" address = ":8080" protocol = "tcp" +logAccess = false diff --git a/internal/conf/conf.go b/internal/conf/conf.go index 64e7688..8815efc 100644 --- a/internal/conf/conf.go +++ b/internal/conf/conf.go @@ -58,6 +58,7 @@ type Config struct { Protocol string Extension string NotesDir string + LogAccess bool } var (