saasitone/container/container.go

84 lines
1.8 KiB
Go
Raw Normal View History

2021-12-03 03:11:01 -08:00
package container
import (
2021-12-05 17:56:38 -08:00
"context"
2021-12-10 17:44:23 -08:00
"database/sql"
2021-12-05 17:56:38 -08:00
"fmt"
2021-12-10 17:44:23 -08:00
"entgo.io/ent/dialect"
entsql "entgo.io/ent/dialect/sql"
2021-12-06 11:53:28 -08:00
"github.com/eko/gocache/v2/cache"
"github.com/eko/gocache/v2/store"
2021-12-05 17:56:38 -08:00
"github.com/go-redis/redis/v8"
2021-12-10 17:44:23 -08:00
_ "github.com/jackc/pgx/v4/stdlib"
2021-12-03 03:11:01 -08:00
"github.com/labstack/echo/v4"
"goweb/config"
2021-12-10 17:44:23 -08:00
"goweb/ent"
2021-12-03 03:11:01 -08:00
)
type Container struct {
2021-12-10 17:44:23 -08:00
Web *echo.Echo
Config *config.Config
Cache *cache.Cache
Database *sql.DB
2021-12-11 10:18:32 -08:00
ORM *ent.Client
2021-12-03 03:11:01 -08:00
}
2021-12-12 18:28:53 -08:00
func NewContainer() *Container {
c := new(Container)
c.initWeb()
c.initConfig()
c.initCache()
c.initDatabase()
c.initORM()
return c
}
2021-12-11 10:18:32 -08:00
func (c *Container) initWeb() {
2021-12-03 03:11:01 -08:00
c.Web = echo.New()
2021-12-11 10:18:32 -08:00
}
2021-12-03 03:11:01 -08:00
2021-12-11 10:18:32 -08:00
func (c *Container) initConfig() {
2021-12-03 03:11:01 -08:00
cfg, err := config.GetConfig()
if err != nil {
2021-12-10 17:44:23 -08:00
c.Web.Logger.Fatalf("failed to load configuration: %v", err)
2021-12-03 03:11:01 -08:00
}
c.Config = &cfg
2021-12-11 10:18:32 -08:00
}
2021-12-03 03:11:01 -08:00
2021-12-11 10:18:32 -08:00
func (c *Container) initCache() {
2021-12-06 11:53:28 -08:00
cacheClient := redis.NewClient(&redis.Options{
2021-12-05 17:56:38 -08:00
Addr: fmt.Sprintf("%s:%d", c.Config.Cache.Hostname, c.Config.Cache.Port),
Password: c.Config.Cache.Password,
})
2021-12-11 10:18:32 -08:00
if _, err := cacheClient.Ping(context.Background()).Result(); err != nil {
2021-12-10 17:44:23 -08:00
c.Web.Logger.Fatalf("failed to connect to cache server: %v", err)
2021-12-05 17:56:38 -08:00
}
2021-12-06 11:53:28 -08:00
cacheStore := store.NewRedis(cacheClient, nil)
c.Cache = cache.New(cacheStore)
2021-12-11 10:18:32 -08:00
}
func (c *Container) initDatabase() {
var err error
2021-12-05 17:56:38 -08:00
2021-12-10 17:44:23 -08:00
addr := fmt.Sprintf("postgresql://%s:%s@%s/%s",
c.Config.Database.User,
c.Config.Database.Password,
c.Config.Database.Hostname,
c.Config.Database.Database,
)
c.Database, err = sql.Open("pgx", addr)
if err != nil {
c.Web.Logger.Fatalf("failed to connect to database: %v", err)
}
2021-12-11 10:18:32 -08:00
}
2021-12-10 17:44:23 -08:00
2021-12-11 10:18:32 -08:00
func (c *Container) initORM() {
2021-12-10 17:44:23 -08:00
drv := entsql.OpenDB(dialect.Postgres, c.Database)
2021-12-11 10:18:32 -08:00
c.ORM = ent.NewClient(ent.Driver(drv))
if err := c.ORM.Schema.Create(context.Background()); err != nil {
2021-12-10 17:44:23 -08:00
c.Web.Logger.Fatalf("failed to create database schema: %v", err)
}
2021-12-11 10:18:32 -08:00
}