Files
EdgeAdmin/internal/web/actions/default/settings/database/index.go

84 lines
1.6 KiB
Go
Raw Normal View History

package database
2020-10-11 10:51:13 +08:00
2020-10-11 16:20:55 +08:00
import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
2020-11-24 09:50:22 +08:00
"github.com/go-sql-driver/mysql"
2020-10-11 16:20:55 +08:00
"github.com/iwind/TeaGo/Tea"
"github.com/iwind/TeaGo/dbs"
"github.com/iwind/TeaGo/maps"
2022-03-04 12:35:28 +08:00
"gopkg.in/yaml.v3"
2022-08-04 11:51:34 +08:00
"os"
2020-10-11 16:20:55 +08:00
"strings"
)
2020-10-11 10:51:13 +08:00
type IndexAction struct {
actionutils.ParentAction
}
func (this *IndexAction) Init() {
2020-10-11 16:20:55 +08:00
this.Nav("", "", "index")
2020-10-11 10:51:13 +08:00
}
func (this *IndexAction) RunGet(params struct{}) {
2020-10-11 16:20:55 +08:00
this.Data["error"] = ""
configFile := Tea.ConfigFile("api_db.yaml")
2022-08-04 11:51:34 +08:00
data, err := os.ReadFile(configFile)
2020-10-11 16:20:55 +08:00
if err != nil {
this.Data["error"] = "read config file failed: api_db.yaml: " + err.Error()
this.Show()
return
}
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()
return
}
if config.DBs == nil {
2020-10-13 20:05:29 +08:00
this.Data["error"] = "no database configured in config file: api_db.yaml"
2020-10-11 16:20:55 +08:00
this.Show()
return
}
2020-10-13 20:05:29 +08:00
var dbConfig *dbs.DBConfig
for _, db := range config.DBs {
dbConfig = db
break
2020-10-11 16:20:55 +08:00
}
dsn := dbConfig.Dsn
2020-11-24 09:50:22 +08:00
cfg, err := mysql.ParseDSN(dsn)
2020-10-11 16:20:55 +08:00
if err != nil {
2020-11-24 09:50:22 +08:00
this.Data["error"] = "parse dsn error: " + err.Error()
2020-10-11 16:20:55 +08:00
this.Show()
return
}
2020-11-24 09:50:22 +08:00
host := cfg.Addr
2020-10-11 16:20:55 +08:00
port := "3306"
2020-11-24 09:50:22 +08:00
index := strings.LastIndex(host, ":")
2020-10-11 16:20:55 +08:00
if index > 0 {
2020-11-24 09:50:22 +08:00
port = host[index+1:]
host = host[:index]
2020-10-11 16:20:55 +08:00
}
2020-11-24 09:50:22 +08:00
password := cfg.Passwd
2020-10-11 16:20:55 +08:00
if len(password) > 0 {
password = strings.Repeat("*", len(password))
}
this.Data["dbConfig"] = maps.Map{
"host": host,
"port": port,
2020-11-24 09:50:22 +08:00
"username": cfg.User,
2020-10-11 16:20:55 +08:00
"password": password,
2020-11-24 09:50:22 +08:00
"database": cfg.DBName,
2020-10-11 16:20:55 +08:00
}
// TODO 测试连接
2020-10-11 10:51:13 +08:00
this.Show()
}