database/database.go
bryanqiu 17c56cfddf dev
2024-07-01 13:43:56 +08:00

49 lines
1.5 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package database
import (
"fmt"
"strconv"
"strings"
)
type Config struct {
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
}