-
Notifications
You must be signed in to change notification settings - Fork 0
/
doppler.go
140 lines (106 loc) · 2.47 KB
/
doppler.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package dopplergoruntime
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"gopkg.in/yaml.v3"
)
type DopplerRuntime struct {
Token string
Project string
Config string
EnableDebug bool
Result map[string]string
CommonResponse *CommonResponse
}
func (dr *DopplerRuntime) DownloadSecret() ([]byte, error) {
var (
body []byte
err error
)
url := fmt.Sprintf(URL, dr.Token, dr.Project , dr.Config)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return body, err;
}
req.Header.Add("Accept", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return body, err;
}
defer res.Body.Close()
body, err = ioutil.ReadAll(res.Body)
if err != nil {
return body, err;
}
return body, err;
}
func (dr *DopplerRuntime) Parse(jsonByte []byte) error {
return json.Unmarshal(jsonByte, &dr.Result)
}
func (dr *DopplerRuntime) ParseCommon(jsonByte []byte) error {
return json.Unmarshal(jsonByte, &dr.CommonResponse)
}
func (dr *DopplerRuntime) SetEnv() {
for key, val := range(dr.Result) {
os.Setenv(key, val);
}
}
func (dr *DopplerRuntime) Load() error {
res, err := dr.DownloadSecret()
if err != nil {
return err
}
if err = dr.Parse(res); err != nil {
if err = dr.ParseCommon(res); err != nil {
}
if dr.CommonResponse.Success == false {
return errors.New(dr.CommonResponse.Messages[0])
}
}
dr.SetEnv()
if dr.EnableDebug {
fmt.Println(fmt.Sprintf("%v Env Loaded; Project %s; Config %s", len(dr.Result), dr.Project, dr.Config))
}
return nil
}
func loadDopplerYaml (filename string) (dopplerConfig *DopplerConfigYaml) {
yamlFile, err := ioutil.ReadFile(filename)
if err == nil {
err = yaml.Unmarshal(yamlFile, &dopplerConfig)
}
return dopplerConfig
}
func NewDopplerRuntime(opt DopplerRuntimeConfig) *DopplerRuntime {
var (
token string
defaultConfig string = "doppler.yaml"
project string
config string
)
if opt.Token == "" {
token = os.Getenv("DOPPLER_TOKEN")
} else {
token = opt.Token
}
dopplerConfigYaml := loadDopplerYaml(defaultConfig)
if opt.Project == "" {
project = dopplerConfigYaml.Setup.Project
} else {
project = opt.Project
}
if opt.Config == "" {
config = dopplerConfigYaml.Setup.Config
} else {
config = opt.Config
}
return &DopplerRuntime{
Token: token,
Project: project,
Config: config,
EnableDebug: opt.EnableDebug,
}
}