shithub: hell

ref: f02f6adb3fbd547fb52e13b86925469bae0c6a2a
dir: /config.go/

View raw version
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
}