Add first attempt at a middleware
This commit is contained in:
parent
a7763831b5
commit
b92adff355
|
@ -156,3 +156,13 @@ func (w *PrettyZerologWriter) Write(p []byte) (int, error) {
|
||||||
|
|
||||||
return os.Stderr.Write([]byte(b.String()))
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -19,24 +19,16 @@ import (
|
||||||
var WebsiteCommand = &cobra.Command{
|
var WebsiteCommand = &cobra.Command{
|
||||||
Short: "Run the HMN website",
|
Short: "Run the HMN website",
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
defer func() {
|
defer logging.LogPanics()
|
||||||
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")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
logging.Info().Msg("Hello, HMN!")
|
logging.Info().Msg("Hello, HMN!")
|
||||||
|
|
||||||
conn := db.NewConnPool(4, 8)
|
conn := db.NewConnPool(4, 8)
|
||||||
|
|
||||||
router := httprouter.New()
|
router := httprouter.New()
|
||||||
router.GET("/", func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
router.GET("/", WithRequestLogger(func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
||||||
rw.Write([]byte("Hello, HMN!"))
|
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) {
|
router.GET("/project/:id", func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
||||||
id := p.ByName("id")
|
id := p.ByName("id")
|
||||||
row := conn.QueryRow(context.Background(), "SELECT name FROM handmade_project WHERE id = $1", 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue