You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
45 lines
1.1 KiB
45 lines
1.1 KiB
package svc
|
|
|
|
import (
|
|
{{.configImport}}
|
|
// 默认引入 gorm, 方便后续使用
|
|
"gorm.io/gorm"
|
|
// Mysql
|
|
"gorm.io/driver/mysql"
|
|
// Redis
|
|
"github.com/go-redis/redis/v8"
|
|
// fmt
|
|
"fmt"
|
|
)
|
|
|
|
type ServiceContext struct {
|
|
Config {{.config}}
|
|
{{.middleware}}
|
|
DB *gorm.DB
|
|
Redis *redis.Client
|
|
}
|
|
|
|
func NewServiceContext(c {{.config}}) *ServiceContext {
|
|
// 初始化Mysql
|
|
mysql_dns := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", c.MySQL.User, c.MySQL.Password, c.MySQL.Host, c.MySQL.Port, c.MySQL.DBName)
|
|
db, err := gorm.Open(mysql.Open(mysql_dns), &gorm.Config{})
|
|
if err != nil {
|
|
panic(fmt.Sprintf("failed to connect to database: %v", err))
|
|
}
|
|
// 初始化Redis
|
|
redisClient := redis.NewClient(&redis.Options{
|
|
Addr: fmt.Sprintf("%s:%d", c.Redis.Host, c.Redis.Port),
|
|
Password: c.Redis.Password, // no password set
|
|
DB: c.Redis.DB, // use default DB
|
|
})
|
|
_, err = redisClient.Ping(c.Context).Result()
|
|
if err != nil {
|
|
panic(fmt.Sprintf("failed to connect to redis: %v", err))
|
|
}
|
|
return &ServiceContext{
|
|
Config: c,
|
|
{{.middlewareAssignment}}
|
|
DB: db,
|
|
Redis: redisClient,
|
|
}
|
|
}
|
|
|