84 lines
2.3 KiB
Go
84 lines
2.3 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"os/signal"
|
|
"sync"
|
|
"time"
|
|
|
|
"git.haelnorr.com/h/golib/hlog"
|
|
"github.com/pkg/errors"
|
|
|
|
"git.haelnorr.com/h/oslstats/internal/config"
|
|
"git.haelnorr.com/h/oslstats/internal/db"
|
|
"git.haelnorr.com/h/oslstats/internal/discord"
|
|
"git.haelnorr.com/h/oslstats/internal/embedfs"
|
|
"git.haelnorr.com/h/oslstats/internal/server"
|
|
"git.haelnorr.com/h/oslstats/internal/store"
|
|
)
|
|
|
|
// Initializes and runs the server
|
|
func run(ctx context.Context, logger *hlog.Logger, cfg *config.Config) error {
|
|
ctx, cancel := signal.NotifyContext(ctx, os.Interrupt)
|
|
defer cancel()
|
|
|
|
// Setup the database connection
|
|
logger.Debug().Msg("Config loaded and logger started")
|
|
logger.Debug().Msg("Connecting to database")
|
|
conn := db.NewDB(cfg.DB)
|
|
|
|
// Setup embedded files
|
|
logger.Debug().Msg("Getting embedded files")
|
|
staticFS, err := embedfs.GetEmbeddedFS()
|
|
if err != nil {
|
|
return errors.Wrap(err, "getStaticFiles")
|
|
}
|
|
|
|
// Setup session store
|
|
logger.Debug().Msg("Setting up session store")
|
|
store := store.NewStore()
|
|
|
|
// Setup Discord API client
|
|
logger.Debug().Msg("Setting up Discord API client")
|
|
discordAPI, err := discord.NewAPIClient(cfg.Discord, logger, cfg.HWSAuth.TrustedHost)
|
|
if err != nil {
|
|
return errors.Wrap(err, "discord.NewAPIClient")
|
|
}
|
|
|
|
logger.Debug().Msg("Setting up HTTP server")
|
|
httpServer, err := server.Setup(staticFS, cfg, logger, conn, store, discordAPI)
|
|
if err != nil {
|
|
return errors.Wrap(err, "setupHttpServer")
|
|
}
|
|
|
|
// Runs the http server
|
|
logger.Debug().Msg("Starting up the HTTP server")
|
|
err = httpServer.Start(ctx)
|
|
if err != nil {
|
|
return errors.Wrap(err, "httpServer.Start")
|
|
}
|
|
|
|
// Handles graceful shutdown
|
|
var wg sync.WaitGroup
|
|
wg.Go(func() {
|
|
<-ctx.Done()
|
|
shutdownCtx := context.Background()
|
|
shutdownCtx, cancel := context.WithTimeout(shutdownCtx, 60*time.Second)
|
|
defer cancel()
|
|
logger.Info().Msg("Shut down requested, waiting 60 seconds...")
|
|
err := httpServer.Shutdown(shutdownCtx)
|
|
if err != nil {
|
|
logger.Error().Err(err).Str("stacktrace", fmt.Sprintf("%+v", errors.Wrap(err, "httpServer.Shutdown"))).Msg("Error during HTTP server shutdown")
|
|
}
|
|
err = conn.Close()
|
|
if err != nil {
|
|
logger.Error().Err(err).Str("stacktrace", fmt.Sprintf("%+v", errors.Wrap(err, "closedb"))).Msg("Error during database close")
|
|
}
|
|
})
|
|
wg.Wait()
|
|
logger.Info().Msg("Shutting down")
|
|
return nil
|
|
}
|