This commit is contained in:
2024-10-17 23:52:10 +08:00
commit 1e92c359f4
14 changed files with 447 additions and 0 deletions

26
config/db.go Normal file
View File

@ -0,0 +1,26 @@
package config
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"log"
)
var DB *gorm.DB
func InitDB() {
var err error
// "%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local"
dsn := fmt.Sprintf(
"%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
Conf.DB.User,
Conf.DB.Passwd,
Conf.DB.Host,
Conf.DB.Port,
Conf.DB.Database)
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatalf("无法连接到数据库: %v", err)
}
}

31
config/readConfig.go Normal file
View File

@ -0,0 +1,31 @@
package config
import "github.com/BurntSushi/toml"
type Config struct {
Server ServerConfig `toml:"server"`
DB DBConfig `toml:"db"`
}
type ServerConfig struct {
Port int `toml:"port"`
}
type DBConfig struct {
Host string `toml:"host"`
Port int `toml:"port"`
Database string `toml:"database"`
User string `toml:"user"`
Passwd string `toml:"passwd"`
}
var Conf *Config
func ReadConfig(path string) error {
var c Config
if _, err := toml.DecodeFile(path, &c); err != nil {
return err
}
Conf = &c
return nil
}