This commit is contained in:
bryanqiu 2024-07-01 13:43:56 +08:00
parent 316f516e9b
commit 17c56cfddf

View File

@ -1,11 +1,48 @@
package database package database
import (
"fmt"
"strconv"
"strings"
)
type Config struct { type Config struct {
Host string `toml:"host"` //数据库名称 Type string `toml:"type"` //数据库类型 mysql or pgsql
Port int `toml:"port"` //数据库名称 Host string `toml:"host"` //数据库名称
Debug bool `toml:"debug"` //调试开关会在日志打印SQL) Port int `toml:"port"` //数据库名称
Dbname string `toml:"dbname"` //数据库名称 Debug bool `toml:"debug"` //调试开关会在日志打印SQL)
Username string `toml:"username"` //数据库用户名 Dbname string `toml:"dbname"` //数据库名称
Password string `toml:"password"` //数据库连接密码 Username string `toml:"username"` //数据库用户名
ExtraParameters string `toml:"extra_parameters"` //数据库连接扩展参数 Password string `toml:"password"` //数据库连接密码
ExtraParameters string `toml:"extra_parameters"` //数据库连接扩展参数
}
func GetDsn(dbcfg *Config) (dsn string) {
switch dbcfg.Type {
case "mysql":
//dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
dsn = fmt.Sprintf(
"%s:%s@tcp(%s:%d)/%s?%s",
dbcfg.Username,
dbcfg.Password,
dbcfg.Host,
dbcfg.Port,
dbcfg.Dbname,
dbcfg.ExtraParameters,
)
case "pgsql":
//dsn := "host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai"
arrConfStr := []string{
"host=" + dbcfg.Host,
"port=" + strconv.Itoa(dbcfg.Port),
"user=" + dbcfg.Username,
"password=" + dbcfg.Password,
"dbname=" + dbcfg.Dbname,
dbcfg.ExtraParameters,
}
dsn = strings.Join(arrConfStr, " ")
default:
panic("DATABASE TYPE '" + dbcfg.Type + "' NOT SUPPORT (only mysql or pgsql)")
}
return dsn
} }