From b92adff355ec67f7c27fdd60b7d74426749f407f Mon Sep 17 00:00:00 2001 From: Ben Visness Date: Wed, 10 Mar 2021 23:02:43 -0600 Subject: [PATCH] Add first attempt at a middleware --- src/logging/logging.go | 10 ++++++++++ src/website/website.go | 30 ++++++++++++++++++------------ 2 files changed, 28 insertions(+), 12 deletions(-) diff --git a/src/logging/logging.go b/src/logging/logging.go index 2181ee2b..7a5a1a0c 100644 --- a/src/logging/logging.go +++ b/src/logging/logging.go @@ -156,3 +156,13 @@ func (w *PrettyZerologWriter) Write(p []byte) (int, error) { return os.Stderr.Write([]byte(b.String())) } + +func LogPanics() { + if r := recover(); r != nil { + if err, ok := r.(error); ok { + Error().Err(err).Msg("recovered from panic") + } else { + Error().Interface("recovered", r).Msg("recovered from panic") + } + } +} diff --git a/src/website/website.go b/src/website/website.go index ee73a529..2b7d9de2 100644 --- a/src/website/website.go +++ b/src/website/website.go @@ -19,24 +19,16 @@ import ( var WebsiteCommand = &cobra.Command{ Short: "Run the HMN website", Run: func(cmd *cobra.Command, args []string) { - defer func() { - if r := recover(); r != nil { - if err, ok := r.(error); ok { - logging.Error().Err(err).Msg("recovered from panic") - } else { - logging.Error().Interface("recovered", r).Msg("recovered from panic") - } - } - }() + defer logging.LogPanics() logging.Info().Msg("Hello, HMN!") conn := db.NewConnPool(4, 8) router := httprouter.New() - router.GET("/", func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) { - rw.Write([]byte("Hello, HMN!")) - }) + router.GET("/", WithRequestLogger(func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) { + rw.Write([]byte(fmt.Sprintf("Hello, HMN! The time is: %v\n", time.Now()))) + })) router.GET("/project/:id", func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) { id := p.ByName("id") row := conn.QueryRow(context.Background(), "SELECT name FROM handmade_project WHERE id = $1", p.ByName("id")) @@ -74,3 +66,17 @@ var WebsiteCommand = &cobra.Command{ } }, } + +func WithRequestLogger(h httprouter.Handle) httprouter.Handle { + return func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) { + defer logging.LogPanics() + + start := time.Now() + defer func() { + end := time.Now() + logging.Info().Dur("duration", end.Sub(start)).Msg("Completed request") + }() + + h(rw, r, p) + } +}