ref: 3bf4db591828464cac77a8555359b38c233c3bce
dir: /config.go/
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
const configFileName = "config.json"
type account struct {
MASTODON_CLIENT_ID string `json:"MASTODON_CLIENT_ID"`
MASTODON_CLIENT_SECRET string `json:"MASTODON_CLIENT_SECRET"`
MASTODON_ACCESS_TOKEN string `json:"MASTODON_ACCESS_TOKEN"`
URL string `json:"URL"`
}
func loadConfig() (*account, error) {
config := &account{}
// Check if the config file exists
if _, err := os.Stat(configFileName); os.IsNotExist(err) {
// no config, create account
client := ConfigureClient()
config.URL = "https://eldritch.cafe"
config.MASTODON_CLIENT_ID = client.Config.ClientID
config.MASTODON_CLIENT_SECRET = client.Config.ClientSecret
config.MASTODON_ACCESS_TOKEN = client.Config.AccessToken
data, err := json.MarshalIndent(config, "", " ")
if err != nil {
return nil, fmt.Errorf("error marshalling config: %w", err)
}
err = ioutil.WriteFile(configFileName, data, 0644)
if err != nil {
return nil, fmt.Errorf("error writing config file: %w", err)
}
return config, nil
}
// File exists, load it
data, err := ioutil.ReadFile(configFileName)
if err != nil {
return nil, fmt.Errorf("error reading config file: %w", err)
}
err = json.Unmarshal(data, config)
if err != nil {
return nil, fmt.Errorf("error unmarshalling config: %w", err)
}
return config, nil
}