hmn/src/website/website.go

71 lines
1.6 KiB
Go
Raw Normal View History

2021-03-09 08:05:07 +00:00
package website
import (
"context"
2021-03-11 03:29:32 +00:00
"errors"
2021-03-09 08:05:07 +00:00
"net/http"
2021-03-11 03:29:32 +00:00
"os"
"os/signal"
"time"
2021-03-09 08:05:07 +00:00
2021-03-11 03:39:24 +00:00
"git.handmade.network/hmn/hmn/src/config"
"git.handmade.network/hmn/hmn/src/db"
"git.handmade.network/hmn/hmn/src/logging"
2021-03-14 20:49:58 +00:00
"git.handmade.network/hmn/hmn/src/templates"
2021-03-09 08:05:07 +00:00
"github.com/julienschmidt/httprouter"
"github.com/spf13/cobra"
)
var WebsiteCommand = &cobra.Command{
Short: "Run the HMN website",
Run: func(cmd *cobra.Command, args []string) {
2021-03-14 20:49:58 +00:00
templates.Init()
2021-03-11 05:02:43 +00:00
defer logging.LogPanics()
2021-03-11 03:19:39 +00:00
logging.Info().Msg("Hello, HMN!")
2021-03-09 08:05:07 +00:00
conn := db.NewConnPool(4, 8)
2021-03-11 03:29:32 +00:00
server := http.Server{
Addr: config.Config.Addr,
2021-03-14 20:49:58 +00:00
Handler: NewWebsiteRoutes(conn),
2021-03-11 03:29:32 +00:00
}
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
go func() {
<-signals
logging.Info().Msg("Shutting down the website")
timeout, _ := context.WithTimeout(context.Background(), 30*time.Second)
server.Shutdown(timeout)
<-signals
logging.Warn().Msg("Forcibly killed the website")
os.Exit(1)
}()
2021-03-11 03:19:39 +00:00
logging.Info().Str("addr", config.Config.Addr).Msg("Serving the website")
2021-03-11 03:29:32 +00:00
serverErr := server.ListenAndServe()
if !errors.Is(serverErr, http.ErrServerClosed) {
logging.Error().Err(serverErr).Msg("Server shut down unexpectedly")
}
2021-03-09 08:05:07 +00:00
},
}
2021-03-11 05:02:43 +00:00
2021-03-14 20:49:58 +00:00
func withRequestLogger(h httprouter.Handle) httprouter.Handle {
2021-03-11 05:02:43 +00:00
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)
}
}
2021-03-14 20:49:58 +00:00
// func handleRequestResults