config.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package global
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "github.com/BurntSushi/toml"
  7. )
  8. type Config struct {
  9. App AppConfig `toml:"config"`
  10. Logs LogConfig `toml:"logs"`
  11. }
  12. type AppConfig struct {
  13. Ip string `toml:"ip"`
  14. Port string `toml:"port"`
  15. }
  16. type LogConfig struct {
  17. AppLog string `toml:"app_log"`
  18. }
  19. func fileExists(filePath string) bool {
  20. _, err := os.Stat(filePath)
  21. if os.IsNotExist(err) {
  22. return false
  23. }
  24. return err == nil
  25. }
  26. func createFileWithContent(filePath, content string) error {
  27. return os.WriteFile(filePath, []byte(content), 0644)
  28. }
  29. // LoadConfig 从给定的 TOML 文件路径加载配置
  30. func LoadConfig(filePath string) *Config {
  31. var config Config
  32. if !fileExists(filePath) {
  33. content := `[config]
  34. ip = "127.0.0.1"
  35. port = "8080"
  36. [logs]
  37. app_log = "./logs"
  38. `
  39. err := createFileWithContent(filePath, content)
  40. if err != nil {
  41. fmt.Printf("创建文件失败: %v\n", err)
  42. } else {
  43. fmt.Printf("文件 %s 已成功创建\n", filePath)
  44. }
  45. }
  46. // 读取并解析 TOML 文件
  47. if _, err := toml.DecodeFile(filePath, &config); err != nil {
  48. log.Fatalf("无法解析配置文件: %s", err)
  49. }
  50. return &config
  51. }