package config import ( "encoding/json" "flag" "io/ioutil" "log" "os" ) type Config struct { User User `json:"user"` ServerTS ServerTS `json:"serverTS"` ServerWeb ServerWeb `json:"serverWeb"` } type User struct { Name string `json:"name"` Password string `json:"password"` } type ServerTS struct { IP string `json:"ip"` PortServer uint16 `json:"portServer"` PortQuery uint16 `json:"portQuery"` } type ServerWeb struct { Port uint16 `json:"port"` } const FileName = "config.json" func New() (*Config, error) { config := defaults() configFile, err := os.Open(FileName) if err != nil { if err := config.createFile(); err != nil { return nil, err } log.Println(config) return &config, nil } defer configFile.Close() jsonParser := json.NewDecoder(configFile) jsonParser.Decode(&config) config.overrideWithFlags() return &config, nil } func (config Config) createFile() error { configJSON, err := json.MarshalIndent(config, "", " ") if err != nil { return err } return ioutil.WriteFile(FileName, configJSON, 0644) } func defaults() Config { return Config{ User: User{ Name: "serveradmin", Password: "", }, ServerTS: ServerTS{ IP: "127.0.0.1", PortServer: 9987, PortQuery: 10011, }, ServerWeb: ServerWeb{ Port: 80, }, } } func (config *Config) overrideWithFlags() { username := flag.String("ts3_name", "", "TS3Query username") password := flag.String("ts3_pw", "", "TS3Query user password") tsIP := flag.String("ts3_ip", "", "TS3 IP address") tsPort := flag.Uint64("ts3_port", 65536, "TS3 port") tsQuery := flag.Uint64("ts3_query", 65536, "TS3 query port") webPort := flag.Uint64("web_port", 65536, "Webserver port") flag.Parse() if *username != "" { config.User.Name = *username } if *password != "" { config.User.Password = *password } if *tsIP != "" { config.ServerTS.IP = *tsIP } if *tsPort <= 65535 { config.ServerTS.PortServer = uint16(*tsPort) } if *tsQuery <= 65535 { config.ServerTS.PortQuery = uint16(*tsQuery) } if *webPort <= 65535 { config.ServerWeb.Port = uint16(*webPort) } }