|
| 1 | +package board |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "github.com/pkg/errors" |
| 6 | + "gopkg.in/yaml.v2" |
| 7 | + "io/ioutil" |
| 8 | + "log" |
| 9 | + "os" |
| 10 | + "path/filepath" |
| 11 | + "time" |
| 12 | +) |
| 13 | + |
| 14 | +// ConnectionConfig contains parameters for multicast -> websocket connections |
| 15 | +type ConnectionConfig struct { |
| 16 | + SubscribePath string `yaml:"SubscribePath"` |
| 17 | + SendingInterval time.Duration `yaml:"SendingInterval"` |
| 18 | + MulticastAddress string `yaml:"MulticastAddress"` |
| 19 | +} |
| 20 | + |
| 21 | +// RefereeConfig contains referee specific connection parameters |
| 22 | +type RefereeConfig struct { |
| 23 | + ConnectionConfig `yaml:"Connection"` |
| 24 | +} |
| 25 | + |
| 26 | +// Config is the root config containing all configs for the server |
| 27 | +type Config struct { |
| 28 | + ListenAddress string `yaml:"ListenAddress"` |
| 29 | + RefereeConnection RefereeConfig `yaml:"RefereeConfig"` |
| 30 | +} |
| 31 | + |
| 32 | +// String converts the config to a string |
| 33 | +func (c Config) String() string { |
| 34 | + str, err := json.Marshal(c) |
| 35 | + if err != nil { |
| 36 | + return err.Error() |
| 37 | + } |
| 38 | + return string(str) |
| 39 | +} |
| 40 | + |
| 41 | +// ReadConfig reads the server config from a yaml file |
| 42 | +func ReadConfig(fileName string) (config Config, err error) { |
| 43 | + config = DefaultConfig() |
| 44 | + f, err := os.Open(fileName) |
| 45 | + if err != nil { |
| 46 | + return |
| 47 | + } |
| 48 | + d, err := ioutil.ReadAll(f) |
| 49 | + if err != nil { |
| 50 | + log.Fatalln("Could not read config file: ", err) |
| 51 | + } |
| 52 | + err = yaml.Unmarshal(d, &config) |
| 53 | + if err != nil { |
| 54 | + log.Fatalln("Could not unmarshal config file: ", err) |
| 55 | + } |
| 56 | + return |
| 57 | +} |
| 58 | + |
| 59 | +// WriteTo writes the config to the specified file |
| 60 | +func (c *Config) WriteTo(fileName string) (err error) { |
| 61 | + b, err := yaml.Marshal(c) |
| 62 | + if err != nil { |
| 63 | + err = errors.Wrapf(err, "Could not marshal config %v", c) |
| 64 | + return |
| 65 | + } |
| 66 | + err = os.MkdirAll(filepath.Dir(fileName), 0755) |
| 67 | + if err != nil { |
| 68 | + err = errors.Wrapf(err, "Could not create directly for config file: %v", fileName) |
| 69 | + return |
| 70 | + } |
| 71 | + err = ioutil.WriteFile(fileName, b, 0600) |
| 72 | + return |
| 73 | +} |
| 74 | + |
| 75 | +// DefaultConfig creates a config instance filled with default values |
| 76 | +func DefaultConfig() Config { |
| 77 | + return Config{ |
| 78 | + ListenAddress: ":8082", |
| 79 | + RefereeConnection: RefereeConfig{ |
| 80 | + ConnectionConfig: ConnectionConfig{ |
| 81 | + MulticastAddress: "224.5.23.1:10003", |
| 82 | + SendingInterval: time.Millisecond * 100, |
| 83 | + SubscribePath: "/api/referee", |
| 84 | + }, |
| 85 | + }, |
| 86 | + } |
| 87 | +} |
0 commit comments