config.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "time"
  7. "github.com/pelletier/go-toml/v2"
  8. )
  9. type Config struct {
  10. // System Identification
  11. Name string // The name to refer to this BBS
  12. Sysop string // The name to identify the System Operator (SYSOP)
  13. // Paths
  14. DataPath string // Path to users.db, and various *.toml config files
  15. MessagePath string // Path to store *.db (for all message bases: local, NETWORKs)
  16. FilePath string // Path to store files (for both NETWORK-received, and local-received)
  17. LogPath string // Path to store *.log files (for lunarhub.log, and more)
  18. }
  19. func DefaultConfig() *Config {
  20. cfg := &Config{
  21. Name: "Lunar Hub",
  22. Sysop: "Sysop",
  23. DataPath: "data",
  24. MessagePath: "msgs",
  25. FilePath: "files",
  26. LogPath: "logs",
  27. }
  28. cfg.Save()
  29. return cfg
  30. }
  31. func LoadConfig() *Config {
  32. in, err := os.ReadFile("lunar_hub.toml")
  33. if err != nil {
  34. if errors.Is(err, os.ErrNotExist) {
  35. return DefaultConfig()
  36. } else {
  37. panic(fmt.Errorf("load config >> %v", err))
  38. }
  39. }
  40. var data map[string]any = map[string]any{}
  41. err = toml.Unmarshal(in, &data)
  42. if err != nil {
  43. return DefaultConfig()
  44. }
  45. paths := data["Paths"].(map[string]any)
  46. return &Config{
  47. Name: data["Name"].(string),
  48. Sysop: data["Sysop"].(string),
  49. DataPath: paths["Data"].(string),
  50. MessagePath: paths["Messages"].(string),
  51. FilePath: paths["Files"].(string),
  52. LogPath: paths["Logs"].(string),
  53. }
  54. }
  55. func (cfg *Config) Save() error {
  56. f, err := os.Create("lunar_hub.toml")
  57. if err != nil {
  58. return err
  59. }
  60. now := time.Now().Truncate(time.Second).String()
  61. f.WriteString("# Lunar Hub - Main Config\n")
  62. f.WriteString("# Generated: " + now + "\n\n")
  63. f.WriteString("Name = \"" + cfg.Name + "\"\n")
  64. f.WriteString("Sysop = \"" + cfg.Sysop + "\"\n\n")
  65. f.WriteString("[Paths]\n")
  66. f.WriteString("\"Data\" = \"" + cfg.DataPath + "\"\n")
  67. f.WriteString("\"Messages\" = \"" + cfg.MessagePath + "\"\n")
  68. f.WriteString("\"Files\" = \"" + cfg.FilePath + "\"\n")
  69. f.WriteString("\"Logs\" = \"" + cfg.LogPath + "\"\n")
  70. return f.Close()
  71. }