feat(go-swagger): Improve main.go template
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Matthieu 'JP' DERASSE
2023-01-10 23:01:23 +00:00
parent 9683e21ed4
commit 5f6d8a8cec
4 changed files with 78 additions and 76 deletions

View File

@ -11,8 +11,11 @@ import (
"github.com/sirupsen/logrus"
"git.dev.m-and-m.ovh/mderasse/gocommon/commonctx"
"git.dev.m-and-m.ovh/mderasse/gocommon/log"
"git.dev.m-and-m.ovh/mderasse/gocommon/server"
"git.dev.m-and-m.ovh/mderasse/gocommon/tracing"
"git.dev.m-and-m.ovh/mderasse/gocommon/webserver"
"{{ index .DefaultImports "restapi"}}"
)
@ -33,6 +36,14 @@ func main() {
logrus.WithError(err).Fatal("fail to initialize gocommon.log")
}
// Add common environment variables to logger fields
logger, err = log.AddCommonFieldsFromEnv(logger)
if err != nil {
logrus.WithError(err).Fatal("fail to add common environment variables to logger fields")
}
ctx = commonctx.AddMainLogger(ctx, logger)
// Initialize listenAddress
listenAddress, err := server.GetListenAddressFromEnvOrFlags()
if err != nil {
@ -68,31 +79,17 @@ func main() {
}
srv := http.Server{
Addr: listenAddress,
Handler: h,
IdleTimeout: 30 * time.Second,
ReadHeaderTimeout: 2 * time.Second,
ReadTimeout: 1 * time.Second,
WriteTimeout: 1 * time.Second,
Addr: listenAddress,
Handler: h,
}
go func() {
if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
logger.WithError(err).Fatalf("HTTP server error: %v", err)
}
logger.Info("Stopped serving new connections.")
}()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
shutdownCtx, shutdownRelease := context.WithTimeout(ctx, 10*time.Second)
defer shutdownRelease()
if err := srv.Shutdown(shutdownCtx); err != nil {
logger.WithError(err).Fatalf("HTTP shutdown error: %v", err)
err = webserver.ExecuteServer(ctx, &srv, &webserver.ExecuteServerParams{
Cleanup: func() error {
tp.Shutdown(ctx)
return nil
},
})
if err != nil {
logger.WithError(err).Fatal("Failed to run webserver")
}
tp.Shutdown(ctx)
logger.Info("Graceful shutdown complete.")
}