Skip to content

Commit

Permalink
close (opened) database connection
Browse files Browse the repository at this point in the history
  • Loading branch information
muharihar committed Aug 19, 2020
1 parent b72e446 commit b1cf390
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
1 change: 1 addition & 0 deletions interface/restapi/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ func StartRestAPIServer() error {
// fmt.Errorf("StartRestAPIServer.initializeSystems: %s", err.Error())
return err
}
defer initialize.CloseDBConnections(superHandler)

// init echo server
e := echo.New()
Expand Down
5 changes: 5 additions & 0 deletions system/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ func (h *Handler) GetGormDB(conName string) (*gorm.DB, error) {
return db, nil
}

// GetGormDBs get Gorm Databases
func (h *Handler) GetGormDBs() map[string]*gorm.DB {
return h.dbGorms
}

// SetCasbinEnforcer set CasbinEnforcer
func (h *Handler) SetCasbinEnforcer(ceName string, ce *casbin.Enforcer) {
if h.casbinEnforcers == nil {
Expand Down
13 changes: 13 additions & 0 deletions system/initialize/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package initialize

import (
"errors"
"fmt"
"reflect"

// "github.com/jinzhu/gorm"
Expand Down Expand Up @@ -101,3 +102,15 @@ func openDBConnection(driverName, dataSourceName string) (*gorm.DB, error) {
}
return db, err
}

// CloseDBConnections close DB Connections
func CloseDBConnections(h *handler.Handler) {
gorms := h.GetGormDBs()
for key, db := range gorms {
dbCon, _ := db.DB()
fmt.Printf("Closing DB Connection `%s`\n", key)
if err := dbCon.Close(); err != nil {
fmt.Printf("Error while closing DB Connection `%s`: %s\n", key, err.Error())
}
}
}

0 comments on commit b1cf390

Please sign in to comment.