123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- package global
- import (
- "fmt"
- "log"
- "os"
- "github.com/BurntSushi/toml"
- )
- type Config struct {
- App AppConfig `toml:"config"`
- Logs LogConfig `toml:"logs"`
- }
- type AppConfig struct {
- Ip string `toml:"ip"`
- Port string `toml:"port"`
- }
- type LogConfig struct {
- AppLog string `toml:"app_log"`
- }
- func fileExists(filePath string) bool {
- _, err := os.Stat(filePath)
- if os.IsNotExist(err) {
- return false
- }
- return err == nil
- }
- func createFileWithContent(filePath, content string) error {
- return os.WriteFile(filePath, []byte(content), 0644)
- }
- // LoadConfig 从给定的 TOML 文件路径加载配置
- func LoadConfig(filePath string) *Config {
- var config Config
- if !fileExists(filePath) {
- content := `[config]
- ip = "127.0.0.1"
- port = "8080"
- [logs]
- app_log = "./logs"
- `
- err := createFileWithContent(filePath, content)
- if err != nil {
- fmt.Printf("创建文件失败: %v\n", err)
- } else {
- fmt.Printf("文件 %s 已成功创建\n", filePath)
- }
- }
- // 读取并解析 TOML 文件
- if _, err := toml.DecodeFile(filePath, &config); err != nil {
- log.Fatalf("无法解析配置文件: %s", err)
- }
- return &config
- }
|