DB640/internal/config/config.go

102 lines
1.8 KiB
Go
Raw Normal View History

2020-03-23 22:56:41 +00:00
package config
import (
"bytes"
"errors"
"io/ioutil"
"log"
"os"
"github.com/BurntSushi/toml"
)
// Config main type
type Config struct {
2020-04-11 03:16:48 +00:00
Features Features
2020-04-05 20:06:15 +00:00
Web Web
2020-03-24 14:50:49 +00:00
Twitter Twitter
2020-03-26 17:11:12 +00:00
Telegram Telegram
2020-03-24 14:50:49 +00:00
Database Database
2020-03-23 22:56:41 +00:00
}
// Twitter related config
type Twitter struct {
ConsumerKey string
ConsumerSecret string
AccessKey string
AccessSecret string
2020-03-24 14:50:49 +00:00
MagicHashtag string
}
2020-03-26 17:11:12 +00:00
// Telegram related config
type Telegram struct {
APIKey string
}
2020-03-24 14:50:49 +00:00
// Database related config
type Database struct {
Dialect string
Connection string
2020-03-23 22:56:41 +00:00
}
2020-04-05 20:06:15 +00:00
// Web related config
type Web struct {
BindUnix bool
Bind string
WebDir string
}
2020-04-11 03:16:48 +00:00
// Features related config
type Features struct {
Bot bool
Web bool
}
2020-03-23 22:56:41 +00:00
// C holds the loaded configuration
var C Config
// LoadDefaults puts default values into C
func LoadDefaults() {
2020-04-11 03:16:48 +00:00
C.Features.Bot = true
C.Features.Web = true
2020-04-05 20:06:15 +00:00
C.Web.BindUnix = false
C.Web.Bind = ":8080"
C.Web.WebDir = "./web"
2020-03-23 22:56:41 +00:00
C.Twitter.AccessKey = "ACCESSKEY"
C.Twitter.AccessSecret = "ACCESSSECRET"
C.Twitter.ConsumerKey = "CONSUMERKEY"
C.Twitter.ConsumerSecret = "CONSUMERSECRET"
2020-03-24 14:50:49 +00:00
C.Twitter.MagicHashtag = "#DB640"
2020-03-26 17:11:12 +00:00
C.Telegram.APIKey = "APIKEY"
2020-03-24 14:50:49 +00:00
C.Database.Dialect = "sqlite3"
C.Database.Connection = ":memory:"
2020-03-23 22:56:41 +00:00
}
// LoadConfig loads the configuration from given path
func LoadConfig(path string) error {
2020-04-11 03:16:48 +00:00
LoadDefaults()
2020-03-23 22:56:41 +00:00
_, 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
}