You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
OneAuth/cfg/cfg.go

134 lines
2.5 KiB
Go

3 years ago
package cfg
import (
3 years ago
"context"
3 years ago
"fmt"
3 years ago
"github.com/olivere/elastic/v7"
"github.com/olivere/elastic/v7/config"
3 years ago
"github.com/veypi/utils/cmd"
3 years ago
"github.com/veypi/utils/log"
3 years ago
"gorm.io/driver/mysql"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/schema"
3 years ago
)
var Path = cmd.GetCfgPath("oa", "settings")
3 years ago
var Ctx, Cancel = context.WithCancel(context.Background())
3 years ago
var CFG = &struct {
3 years ago
AdminUser string
Host string
LoggerPath string
LoggerLevel string
APPUUID string
APPKey []byte
3 years ago
TimeFormat string
TimeZone string
Debug bool
FileUrlPrefix string
FireDir string
DB struct {
3 years ago
Type string
Addr string
User string
Pass string
DB string
}
3 years ago
ES *config.Config
3 years ago
}{
3 years ago
APPUUID: "jU5Jo5hM",
APPKey: []byte("cB43wF94MLTksyBK"),
3 years ago
AdminUser: "admin",
Host: "0.0.0.0:4001",
LoggerPath: "",
LoggerLevel: "debug",
TimeFormat: "2006/01/02 15:04:05",
TimeZone: "Asia/Shanghai",
Debug: true,
FileUrlPrefix: "/file",
FireDir: "/Users/light/test/media/",
3 years ago
DB: struct {
Type string
Addr string
User string
Pass string
DB string
}{
//Type: "sqlite",
Addr: "127.0.0.1:3306",
//Addr: "oa.db",
3 years ago
User: "root",
Pass: "123456",
DB: "one_auth",
},
3 years ago
ES: &config.Config{
URL: "http://127.0.0.1:9200",
Index: "",
Username: "",
Password: "",
Shards: 0,
Replicas: 0,
Sniff: nil,
Healthcheck: nil,
},
3 years ago
}
var (
db *gorm.DB
)
func DB() *gorm.DB {
if db == nil {
ConnectDB()
}
return db
}
var gormCfg = &gorm.Config{
NamingStrategy: schema.NamingStrategy{
SingularTable: false, // 使用单数表名,启用该选项后,`User` 表将是`user`
NoLowerCase: true,
},
}
3 years ago
func ConnectDB() *gorm.DB {
var err error
conn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local", CFG.DB.User, CFG.DB.Pass, CFG.DB.Addr, CFG.DB.DB)
if CFG.DB.Type == "sqlite" {
conn = CFG.DB.Addr
db, err = gorm.Open(sqlite.Open(conn), gormCfg)
3 years ago
} else {
db, err = gorm.Open(mysql.Open(conn), gormCfg)
3 years ago
}
if err != nil {
panic(err)
}
return db
}
3 years ago
var es *elastic.Client
func ES() *elastic.Client {
if es == nil {
ConnectES()
}
return es
}
func ConnectES() *elastic.Client {
var err error
es, err = elastic.NewClientFromConfig(CFG.ES)
if err != nil {
log.Warn().Msgf("connect es failed: %s", err)
return nil
3 years ago
}
_, _, err = es.Ping("http://127.0.0.1:9200").Do(context.Background())
if err != nil {
// Handle error
log.Warn().Msgf("connect es failed: %s", err)
}
return es
}