config.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package main
  2. import (
  3. "fmt"
  4. "gopkg.in/yaml.v3"
  5. "os"
  6. )
  7. type ServerConfig struct {
  8. Port int `yaml:"port"`
  9. }
  10. func (s *ServerConfig) Addr() string {
  11. ip := "0.0.0.0"
  12. return fmt.Sprintf("%s:%d", ip, s.Port)
  13. }
  14. type MySQLConfig struct {
  15. Host string `yaml:"host"`
  16. Port int `yaml:"port"`
  17. User string `yaml:"user"`
  18. Password string `yaml:"password"`
  19. DBName string `yaml:"dbname"`
  20. }
  21. // DSN returns the Data Source Name for connecting to the MySQL database
  22. // with UTF8 encoding and the local timezone.
  23. func (m *MySQLConfig) DSN() string {
  24. return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", m.User, m.Password, m.Host, m.Port, m.DBName)
  25. }
  26. type Config struct {
  27. Server ServerConfig `yaml:"server"`
  28. MySQL MySQLConfig `yaml:"mysql"`
  29. }
  30. // LoadConfig parses the configuration file and returns a Config instance
  31. func LoadConfig(filePath string) (*Config, error) {
  32. file, err := os.Open(filePath)
  33. if err != nil {
  34. return nil, err
  35. }
  36. defer file.Close()
  37. config := &Config{}
  38. decoder := yaml.NewDecoder(file)
  39. if err := decoder.Decode(config); err != nil {
  40. return nil, err
  41. }
  42. return config, nil
  43. }