-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconfig.go
58 lines (45 loc) · 1.2 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"encoding/json"
"fmt"
"os"
"github.com/adrg/xdg"
)
const (
ConfigurationFilePath = "mataroa-cli/config.json"
EnvVariableApiUrl = "MATAROA_API_URL"
EnvVariableToken = "MATAROA_TOKEN"
)
type Config struct {
ApiUrl string `json:"api_url"`
Token string `json:"token"`
}
func LoadConfiguration() (Config, error) {
var config Config
filePath, err := xdg.ConfigFile(ConfigurationFilePath)
if err != nil {
return config, fmt.Errorf("error finding config file: %s", err)
}
f, err := os.ReadFile(filePath)
if err != nil {
return config, fmt.Errorf("error reading config file: %s", err)
}
err = json.Unmarshal(f, &config)
if err != nil {
return config, fmt.Errorf("error unmarshaling config file: %s", err)
}
if config.ApiUrl == "" {
config.ApiUrl = "https://mataroa.blog/api"
}
if config.Token == "" {
return config, fmt.Errorf(`'key' cannot be empty on '%s'`, ConfigurationFilePath)
}
// environment variables will override the configuration file values
if os.Getenv(EnvVariableApiUrl) != "" {
config.ApiUrl = os.Getenv(EnvVariableApiUrl)
}
if os.Getenv(EnvVariableToken) != "" {
config.Token = os.Getenv(EnvVariableToken)
}
return config, nil
}