From 18e102cc8adde39598d60ef47014544ab60b1020 Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Sat, 5 Aug 2023 17:17:26 -0400 Subject: [PATCH] refactor: always ensure the db connection closes by using a defer --- main.go | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/main.go b/main.go index f00ec6a..ea2831b 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,7 @@ package main import ( "context" "embed" + "fmt" "git.lumeweb.com/LumeWeb/portal/config" "git.lumeweb.com/LumeWeb/portal/controller" "git.lumeweb.com/LumeWeb/portal/db" @@ -13,15 +14,18 @@ import ( "git.lumeweb.com/LumeWeb/portal/service/files" "git.lumeweb.com/LumeWeb/portal/shared" "git.lumeweb.com/LumeWeb/portal/tus" + nriris "github.com/iris-contrib/middleware/newrelic" "github.com/iris-contrib/swagger" "github.com/iris-contrib/swagger/swaggerFiles" "github.com/kataras/iris/v12" irisContext "github.com/kataras/iris/v12/context" "github.com/kataras/iris/v12/middleware/cors" "github.com/kataras/iris/v12/mvc" + "github.com/spf13/viper" "go.uber.org/zap" "log" "net/http" + "os" ) // Embed a directory of static files for serving from the app's root path @@ -48,6 +52,13 @@ func main() { // Initialize the database connection db.Init() + defer func() { + err := db.Close() + + if err != nil { + logger.Get().Error("Failed to close db connection", zap.Error(err)) + } + }() logger.Init() files.Init() auth.Init() @@ -66,6 +77,21 @@ func main() { tusHandler := tus.Init() + if viper.IsSet("newrelic.license") { + nrAapp, err := newrelic.NewApplication( + newrelic.ConfigAppName(viper.GetString("newrelic.appname")), + newrelic.ConfigLicense(viper.GetString("newrelic.license")), + newrelic.ConfigAppLogForwardingEnabled(true), + ) + + if nil != err { + fmt.Println(err) + os.Exit(1) + } + + app.Use(nriris.New(nrAapp)) + } + // Register the AccountController with the MVC framework and attach it to the "/api/account" path mvc.Configure(v1.Party("/account"), func(app *mvc.Application) { app.Handle(new(controller.AccountController)) @@ -116,12 +142,6 @@ func main() { }) if err != nil { - logger.Get().Error("Failed starting webserver proof", zap.Error(err)) - } - - err = db.Close() - - if err != nil { - logger.Get().Error("Failed to close db connection", zap.Error(err)) + logger.Get().Error("Failed starting webserver", zap.Error(err)) } }