go-discord-bot / internal / config / config.go
config.go
Raw
package config

import (
	"fmt"

	"github.com/spf13/viper"
)

type ConfigError struct {
	Err error
}

var (
	Token      string  // Store value of Token from config.json
	BotPrefix  string  // Store value of BotPrefix from config.json
	RiotAPIKey string  // Store value of Riot API Key from riot.json
	cfg        *config // Store value extracted from config.json
)

type config struct {
	Port       string `json:"port"`
	Token      string `json:"token"`
	BotPrefix  string `json:"bot_prefix"`
	RiotAPIKey string `json:"riot_api_key"`
}

func ReadConfig() error {
	fmt.Println("Reading config file with Viper...")
	viper.SetConfigFile("../../.env")
	err := viper.ReadInConfig()
	if err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			// Config file not found; ignore error if desired
			fmt.Println(err.Error())
		} else {
			// Config file was found, but another error was produced
			fmt.Printf("Config file found, but another error has occurred: %v\n", err)
		}
	}

	Token = viper.Get("DISCORD_BOT_TOKEN").(string)
	BotPrefix = viper.Get("BOT_PREFIX").(string)
	RiotAPIKey = viper.Get("RIOT_API_KEY").(string)

	return nil
}