travebing/backend/controller/controller.go

60 lines
1.5 KiB
Go
Raw Normal View History

2024-11-19 16:58:21 +08:00
package controller
import (
"fmt"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"pkg.bing89.com/travebing/config"
"pkg.bing89.com/travebing/controller/geo"
"pkg.bing89.com/travebing/controller/plan"
"pkg.bing89.com/travebing/controller/way"
)
type Controller interface {
Ways(plan int) way.Controller
Plans() plan.Controller
}
type controller struct {
db *gorm.DB
cfg *config.Config
}
func New(cfg *config.Config) (Controller, error) {
c := &controller{
cfg: cfg,
}
dsn := fmt.Sprintf("%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", cfg.Database.Auth, cfg.Database.Address, cfg.Database.Name)
opt := &gorm.Config{}
if cfg.Database.ShowLog {
opt.Logger = logger.Default.LogMode(logger.Info)
}
conn, err := gorm.Open(mysql.Open(dsn), opt)
if err != nil {
return nil, err
}
sqlDB, err := conn.DB()
if err != nil {
return nil, err
}
conn.Set("gorm:table_options", "ENGINE=InnoDB CHARACTER SET=utf8mb4 COLLATE=utf8mb4_unicode_ci")
sqlDB.SetConnMaxIdleTime(time.Duration(cfg.Database.MaxIdleTime) * time.Second)
sqlDB.SetConnMaxLifetime(time.Duration(cfg.Database.MaxLifeTime) * time.Second)
sqlDB.SetMaxIdleConns(cfg.Database.MaxIdleConnections)
sqlDB.SetMaxOpenConns(cfg.Database.MaxOpenConnections)
c.db = conn
return c, nil
}
func (c *controller) Ways(plan int) way.Controller {
return way.New(plan, c.db, &c.cfg.Image, geo.New(&c.cfg.Geo))
}
func (c *controller) Plans() plan.Controller {
return plan.New(c.db)
}