home to your local SPACEGIRL 馃挮
arimelody.space
1package controller
2
3import (
4 "errors"
5 "fmt"
6 "os"
7 "strconv"
8
9 "arimelody-web/model"
10
11 "github.com/pelletier/go-toml/v2"
12)
13
14func GetConfig() model.Config {
15 configFile := os.Getenv("ARIMELODY_CONFIG")
16 if configFile == "" {
17 configFile = "config.toml"
18 }
19
20 config := model.Config{
21 BaseUrl: "https://arimelody.space",
22 Host: "0.0.0.0",
23 Port: 8080,
24 TrustedProxies: []string{ "127.0.0.1" },
25 DB: model.DBConfig{
26 Host: "127.0.0.1",
27 Port: 5432,
28 User: "arimelody",
29 Name: "arimelody",
30 },
31 }
32
33 data, err := os.ReadFile(configFile)
34 if err != nil {
35 configOut, _ := toml.Marshal(&config)
36 os.WriteFile(configFile, configOut, os.ModePerm)
37 fmt.Printf(
38 "A default config.toml has been created. " +
39 "Please configure before running again!\n")
40 os.Exit(0)
41 }
42
43 err = toml.Unmarshal([]byte(data), &config)
44 if err != nil {
45 panic(fmt.Sprintf("FATAL: Failed to parse configuration file: %v\n", err))
46 }
47
48 err = handleConfigOverrides(&config)
49 if err != nil {
50 panic(fmt.Sprintf("FATAL: Failed to parse environment variable %v\n", err))
51 }
52
53 return config
54}
55
56func handleConfigOverrides(config *model.Config) error {
57 var err error
58
59 if env, has := os.LookupEnv("ARIMELODY_BASE_URL"); has { config.BaseUrl = env }
60 if env, has := os.LookupEnv("ARIMELODY_HOST"); has { config.Host = env }
61 if env, has := os.LookupEnv("ARIMELODY_PORT"); has {
62 config.Port, err = strconv.ParseInt(env, 10, 0)
63 if err != nil { return errors.New("ARIMELODY_PORT: " + err.Error()) }
64 }
65 if env, has := os.LookupEnv("ARIMELODY_DATA_DIR"); has { config.DataDirectory = env }
66
67 if env, has := os.LookupEnv("ARIMELODY_DB_HOST"); has { config.DB.Host = env }
68 if env, has := os.LookupEnv("ARIMELODY_DB_PORT"); has {
69 config.DB.Port, err = strconv.ParseInt(env, 10, 0)
70 if err != nil { return errors.New("ARIMELODY_DB_PORT: " + err.Error()) }
71 }
72 if env, has := os.LookupEnv("ARIMELODY_DB_NAME"); has { config.DB.Name = env }
73 if env, has := os.LookupEnv("ARIMELODY_DB_USER"); has { config.DB.User = env }
74 if env, has := os.LookupEnv("ARIMELODY_DB_PASS"); has { config.DB.Pass = env }
75
76 if env, has := os.LookupEnv("ARIMELODY_DISCORD_ADMIN_ID"); has { config.Discord.AdminID = env }
77 if env, has := os.LookupEnv("ARIMELODY_DISCORD_CLIENT_ID"); has { config.Discord.ClientID = env }
78 if env, has := os.LookupEnv("ARIMELODY_DISCORD_SECRET"); has { config.Discord.Secret = env }
79
80 if env, has := os.LookupEnv("ARIMELODY_TWITCH_BROADCASTER"); has { config.Twitch.Broadcaster = env }
81 if env, has := os.LookupEnv("ARIMELODY_TWITCH_CLIENT_ID"); has { config.Twitch.ClientID = env }
82 if env, has := os.LookupEnv("ARIMELODY_TWITCH_SECRET"); has { config.Twitch.Secret = env }
83
84 return nil
85}