hmn/src/website/website.go

81 lines
1.9 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-28 04:22:29 +00:00
"git.handmade.network/hmn/hmn/src/auth"
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-04-26 06:56:49 +00:00
"git.handmade.network/hmn/hmn/src/perf"
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/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()
defer logging.LogPanics(nil)
2021-03-11 03:19:39 +00:00
logging.Info().Msg("Hello, HMN!")
2021-03-09 08:05:07 +00:00
2021-04-26 06:56:49 +00:00
backgroundJobContext, cancelBackgroundJobs := context.WithCancel(context.Background())
conn := db.NewConnPool(config.Config.Postgres.MinConn, config.Config.Postgres.MaxConn)
2021-04-26 06:56:49 +00:00
perfCollector := perf.RunPerfCollector(backgroundJobContext)
2021-03-09 08:05:07 +00:00
2021-03-11 03:29:32 +00:00
server := http.Server{
Addr: config.Config.Addr,
2021-04-26 06:56:49 +00:00
Handler: NewWebsiteRoutes(conn, perfCollector),
2021-03-11 03:29:32 +00:00
}
2021-03-28 04:22:29 +00:00
backgroundJobsDone := zipJobs(
auth.PeriodicallyDeleteExpiredSessions(backgroundJobContext, conn),
2021-04-26 06:56:49 +00:00
perfCollector.Done,
2021-03-28 04:22:29 +00:00
)
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")
go func() {
timeout, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
server.Shutdown(timeout)
cancelBackgroundJobs()
}()
2021-03-11 03:29:32 +00:00
<-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-28 04:22:29 +00:00
<-backgroundJobsDone
2021-03-09 08:05:07 +00:00
},
}
2021-03-28 04:22:29 +00:00
func zipJobs(cs ...<-chan struct{}) <-chan struct{} {
out := make(chan struct{})
go func() {
for _, c := range cs {
<-c
}
close(out)
}()
return out
}