/
config.go
83 lines (70 loc) · 2.08 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package config
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"gopkg.in/yaml.v2"
)
const _configVarName string = "KAPILOGIN_CONFIG"
type Config struct {
KapiloginApiEndpoint string `json:"kapiloginApiEndpoint,omitempty" yaml:"kapiloginApiEndpoint,omitempty"`
OidcIssuerUrl string `json:"oidcIssuerUrl,omitempty" yaml:"oidcIssuerUrl,omitempty"`
OidcClientId string `json:"oidcClientId,omitempty" yaml:"oidcClientId,omitempty"`
OidcClientSecret string `json:"oidcClientSecret" yaml:"oidcClientSecret"`
}
func GetConfig(cfgUri string) (*Config, error) {
envValue, exists := os.LookupEnv(_configVarName)
if exists {
cfgUri = envValue
}
if cfgUri == "" {
return nil, errors.New("empty config envVar/flag: " + _configVarName + " . Use 'kapilogin [command] --help' for more information about a command\n")
}
var fileAsBytes []byte
if strings.HasPrefix(cfgUri, "http") {
response, err := http.Get(cfgUri)
if err != nil {
return nil, err
}
fileAsBytes, err = io.ReadAll(response.Body)
if err != nil {
return nil, err
}
} else {
file, err := os.Open(cfgUri)
if err != nil {
return nil, err
}
defer file.Close()
fileAsBytes, err = io.ReadAll(file)
if err != nil {
return nil, err
}
}
var (
config = &Config{}
extension = filepath.Ext(cfgUri)
)
switch extension {
case ".json":
if err := json.Unmarshal(fileAsBytes, config); err != nil {
return nil, fmt.Errorf("failed to create server configuration from file %s: %w", cfgUri, err)
}
case ".yml", ".yaml":
if err := yaml.Unmarshal(fileAsBytes, config); err != nil {
return nil, fmt.Errorf("failed to create server configuration from file %s: %w", cfgUri, err)
}
default:
return nil, errors.New("invalid server configuration file extension, supported: .json|.yml|.yaml")
}
if config.KapiloginApiEndpoint == "" || config.OidcClientId == "" || config.OidcIssuerUrl == "" {
return nil, fmt.Errorf("configuration file is invalid, required fields is not set, empy or misspelled %+v", config)
}
c := config
return c, nil
}