Move logging middleware into internal middleware package
This commit is contained in:
parent
06495fa358
commit
6e56cefe6f
2 changed files with 36 additions and 28 deletions
|
|
@ -33,11 +33,11 @@ func main() {
|
|||
|
||||
etag := middleware.NewETag("static", cacheExpiration)
|
||||
|
||||
router.Handle("/", logger(http.RedirectHandler("/notes/", http.StatusFound)))
|
||||
router.Handle("/notes/", logger(http.StripPrefix("/notes", notesRouter)))
|
||||
router.Handle("/", middleware.LoggingMiddleware(http.RedirectHandler("/notes/", http.StatusFound)))
|
||||
router.Handle("/notes/", middleware.LoggingMiddleware(http.StripPrefix("/notes", notesRouter)))
|
||||
router.Handle(
|
||||
"/static/",
|
||||
logger(
|
||||
middleware.LoggingMiddleware(
|
||||
middleware.StaticEtagMiddleware(
|
||||
*etag,
|
||||
http.FileServer(http.FS(conf.Static)),
|
||||
|
|
@ -51,28 +51,3 @@ 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) {
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
33
internal/middleware/logger.go
Normal file
33
internal/middleware/logger.go
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"forgejo.gwairfelin.com/max/gonotes/internal/conf"
|
||||
)
|
||||
|
||||
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 LoggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue