Added shutdown method to container.

This commit is contained in:
mikestefanello 2021-12-19 13:22:44 -05:00
parent c6c9ed7fd2
commit 85981e75a7
5 changed files with 35 additions and 11 deletions

View file

@ -35,4 +35,4 @@ run:
.PHONY: test .PHONY: test
test: test:
go test ./... go test -p 1 ./...

View file

@ -35,6 +35,9 @@ func TestMain(m *testing.M) {
// Run tests // Run tests
exitVal := m.Run() exitVal := m.Run()
if err := c.Shutdown(); err != nil {
panic(err)
}
os.Exit(exitVal) os.Exit(exitVal)
} }

View file

@ -33,6 +33,9 @@ func TestMain(m *testing.M) {
// Run tests // Run tests
exitVal := m.Run() exitVal := m.Run()
srv.Close() srv.Close()
if err := c.Shutdown(); err != nil {
panic(err)
}
os.Exit(exitVal) os.Exit(exitVal)
} }

View file

@ -24,6 +24,7 @@ type Container struct {
Web *echo.Echo Web *echo.Echo
Config *config.Config Config *config.Config
Cache *cache.Cache Cache *cache.Cache
cacheClient *redis.Client
Database *sql.DB Database *sql.DB
ORM *ent.Client ORM *ent.Client
Mail *mail.Client Mail *mail.Client
@ -42,6 +43,20 @@ func NewContainer() *Container {
return c return c
} }
func (c *Container) Shutdown() error {
if err := c.cacheClient.Close(); err != nil {
return err
}
if err := c.ORM.Close(); err != nil {
return err
}
if err := c.Database.Close(); err != nil {
return err
}
return nil
}
func (c *Container) initConfig() { func (c *Container) initConfig() {
cfg, err := config.GetConfig() cfg, err := config.GetConfig()
if err != nil { if err != nil {
@ -63,14 +78,14 @@ func (c *Container) initWeb() {
} }
func (c *Container) initCache() { func (c *Container) initCache() {
cacheClient := redis.NewClient(&redis.Options{ c.cacheClient = redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%d", c.Config.Cache.Hostname, c.Config.Cache.Port), Addr: fmt.Sprintf("%s:%d", c.Config.Cache.Hostname, c.Config.Cache.Port),
Password: c.Config.Cache.Password, Password: c.Config.Cache.Password,
}) })
if _, err := cacheClient.Ping(context.Background()).Result(); err != nil { if _, err := c.cacheClient.Ping(context.Background()).Result(); err != nil {
panic(fmt.Sprintf("failed to connect to cache server: %v", err)) panic(fmt.Sprintf("failed to connect to cache server: %v", err))
} }
cacheStore := store.NewRedis(cacheClient, nil) cacheStore := store.NewRedis(c.cacheClient, nil)
c.Cache = cache.New(cacheStore) c.Cache = cache.New(cacheStore)
} }

View file

@ -48,5 +48,8 @@ func TestMain(m *testing.M) {
// Run tests // Run tests
exitVal := m.Run() exitVal := m.Run()
if err := c.Shutdown(); err != nil {
panic(err)
}
os.Exit(exitVal) os.Exit(exitVal)
} }