DB640/internal/config/config.go

59 lines
1.1 KiB
Go

package config
import (
"bytes"
"errors"
"io/ioutil"
"log"
"os"
"github.com/BurntSushi/toml"
)
// Config main type
type Config struct {
Twitter Twitter
}
// Twitter related config
type Twitter struct {
ConsumerKey string
ConsumerSecret string
AccessKey string
AccessSecret string
}
// C holds the loaded configuration
var C Config
// LoadDefaults puts default values into C
func LoadDefaults() {
C.Twitter.AccessKey = "ACCESSKEY"
C.Twitter.AccessSecret = "ACCESSSECRET"
C.Twitter.ConsumerKey = "CONSUMERKEY"
C.Twitter.ConsumerSecret = "CONSUMERSECRET"
}
// LoadConfig loads the configuration from given path
func LoadConfig(path string) error {
_, err := toml.DecodeFile(path, &C)
if errors.Is(err, os.ErrNotExist) {
log.Printf("Could not find file \"%s\", using defaults!", path)
LoadDefaults()
err = WriteConfig(path)
return err
}
return err
}
// WriteConfig writes the configuration to the given path
func WriteConfig(path string) error {
buf := new(bytes.Buffer)
err := toml.NewEncoder(buf).Encode(C)
if err != nil {
return err
}
err = ioutil.WriteFile(path, buf.Bytes(), 0644)
return err
}