12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- package main
- import (
- "fmt"
- "gopkg.in/yaml.v3"
- "os"
- )
- type ServerConfig struct {
- Port int `yaml:"port"`
- }
- func (s *ServerConfig) Addr() string {
- ip := "0.0.0.0"
- return fmt.Sprintf("%s:%d", ip, s.Port)
- }
- type MySQLConfig struct {
- Host string `yaml:"host"`
- Port int `yaml:"port"`
- User string `yaml:"user"`
- Password string `yaml:"password"`
- DBName string `yaml:"dbname"`
- }
- // DSN returns the Data Source Name for connecting to the MySQL database
- // with UTF8 encoding and the local timezone.
- func (m *MySQLConfig) DSN() string {
- 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)
- }
- type Config struct {
- Server ServerConfig `yaml:"server"`
- MySQL MySQLConfig `yaml:"mysql"`
- }
- // LoadConfig parses the configuration file and returns a Config instance
- func LoadConfig(filePath string) (*Config, error) {
- file, err := os.Open(filePath)
- if err != nil {
- return nil, err
- }
- defer file.Close()
- config := &Config{}
- decoder := yaml.NewDecoder(file)
- if err := decoder.Decode(config); err != nil {
- return nil, err
- }
- return config, nil
- }
|