mastotool/config.go

71 lines
1.2 KiB
Go
Raw Normal View History

2018-11-22 04:35:51 +01:00
package main
import (
"encoding/json"
"io/ioutil"
)
2022-11-15 17:07:47 +01:00
// Option is a single configuration option.
2018-11-22 04:35:51 +01:00
type Option struct {
Name string
Value interface{}
}
2022-11-15 17:07:47 +01:00
// Config is a configuration file.
2018-11-22 04:35:51 +01:00
type Config struct {
Options []Option
}
2022-11-15 17:07:47 +01:00
// LoadConfig loads a configuration file.
2018-11-22 04:35:51 +01:00
func LoadConfig(filename string) (Config, error) {
config := Config{}
j, err := ioutil.ReadFile(filename)
if err != nil {
return config, err
}
err = json.Unmarshal(j, &config)
return config, err
}
2022-11-15 17:07:47 +01:00
// Save saves the configuration to a file.
2018-11-22 04:35:51 +01:00
func (c Config) Save(filename string) error {
j, err := json.MarshalIndent(c, "", " ")
if err != nil {
return err
}
2022-11-15 17:07:47 +01:00
return ioutil.WriteFile(filename, j, 0600)
2018-11-22 04:35:51 +01:00
}
2022-11-15 17:07:47 +01:00
// Value returns the value of a configuration option.
2018-11-22 04:35:51 +01:00
func (c Config) Value(name string) interface{} {
for _, v := range c.Options {
if v.Name == name {
return v.Value
}
}
return nil
}
2022-11-15 17:07:47 +01:00
// Set sets the value of a configuration option.
func (c *Config) Set(name, value string) {
2018-11-22 04:35:51 +01:00
found := false
var opts []Option
for _, v := range c.Options {
if v.Name == name {
v.Value = value
found = true
}
opts = append(opts, v)
}
if !found {
opts = append(opts, Option{name, value})
}
c.Options = opts
}