database/database.go

49 lines
1.5 KiB
Go
Raw Normal View History

2024-06-27 11:00:29 +00:00
package database
2024-07-01 05:43:56 +00:00
import (
"fmt"
"strconv"
"strings"
)
2024-06-27 11:00:29 +00:00
type Config struct {
2024-07-01 05:43:56 +00:00
Type string `toml:"type"` //数据库类型 mysql or pgsql
Host string `toml:"host"` //数据库名称
Port int `toml:"port"` //数据库名称
Debug bool `toml:"debug"` //调试开关会在日志打印SQL)
Dbname string `toml:"dbname"` //数据库名称
Username string `toml:"username"` //数据库用户名
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
2024-06-27 11:00:29 +00:00
}