简化API节点的数据库配置(db.yaml)

This commit is contained in:
GoEdgeLab
2024-05-06 17:29:11 +08:00
parent d8e9268dab
commit a573eb5608
8 changed files with 223 additions and 91 deletions

View File

@@ -1,12 +1,14 @@
package database
import (
"github.com/TeaOSLab/EdgeAdmin/internal/configs"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/go-sql-driver/mysql"
"github.com/iwind/TeaGo/Tea"
"github.com/iwind/TeaGo/dbs"
"github.com/iwind/TeaGo/maps"
"gopkg.in/yaml.v3"
"net"
"os"
"strings"
)
@@ -22,7 +24,7 @@ func (this *IndexAction) Init() {
func (this *IndexAction) RunGet(params struct{}) {
this.Data["error"] = ""
configFile := Tea.ConfigFile("api_db.yaml")
var configFile = Tea.ConfigFile("api_db.yaml")
data, err := os.ReadFile(configFile)
if err != nil {
this.Data["error"] = "read config file failed: api_db.yaml: " + err.Error()
@@ -30,8 +32,33 @@ func (this *IndexAction) RunGet(params struct{}) {
return
}
config := &dbs.Config{}
// new config
var config = &configs.SimpleDBConfig{}
err = yaml.Unmarshal(data, config)
if err == nil && len(config.Host) > 0 {
host, port, splitErr := net.SplitHostPort(config.Host)
if splitErr != nil {
port = "3306"
}
this.Data["dbConfig"] = maps.Map{
"host": host,
"port": port,
"username": config.User,
"password": config.Password,
"database": config.Database,
}
this.Show()
return
}
this.parseOldConfig(data)
}
func (this *IndexAction) parseOldConfig(data []byte) {
var config = &dbs.Config{}
err := yaml.Unmarshal(data, config)
if err != nil {
this.Data["error"] = "parse config file failed: api_db.yaml: " + err.Error()
this.Show()
@@ -49,7 +76,12 @@ func (this *IndexAction) RunGet(params struct{}) {
dbConfig = db
break
}
dsn := dbConfig.Dsn
if dbConfig == nil {
this.Data["error"] = "no database configured in config file: api_db.yaml"
this.Show()
return
}
var dsn = dbConfig.Dsn
cfg, err := mysql.ParseDSN(dsn)
if err != nil {
this.Data["error"] = "parse dsn error: " + err.Error()
@@ -57,18 +89,19 @@ func (this *IndexAction) RunGet(params struct{}) {
return
}
host := cfg.Addr
port := "3306"
index := strings.LastIndex(host, ":")
var host = cfg.Addr
var port = "3306"
var index = strings.LastIndex(host, ":")
if index > 0 {
port = host[index+1:]
host = host[:index]
}
password := cfg.Passwd
var password = cfg.Passwd
if len(password) > 0 {
password = strings.Repeat("*", len(password))
}
this.Data["dbConfig"] = maps.Map{
"host": host,
"port": port,