-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenv.go
266 lines (206 loc) · 5.73 KB
/
env.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package env
import (
"fmt"
"io/ioutil"
"os"
"strings"
)
// Env map type
type EnvMap map[string]string
// Map is a struct that contains the map parsed lines from the env file and methods to update the map
type Map struct {
Map EnvMap
}
// Sets the key and value to the map
func (e *Map) Set(key, val string) {
e.Map[key] = val
}
// SetMap reads all keys and values from the EnvMap and sets to another EnvMap.Env
func (e *Map) SetMap(target *Map) {
for key, val := range target.Map {
e.Set(key, val)
}
}
// NewEnvMap creates and returns EnvMap, as well as cretaing the map
func NewMap() *Map {
m := &Map{}
m.Map = make(EnvMap)
return m
}
// Adapter is a interface for pulling secrets from a external secerts storage service (ex. AWS secret manager) and exporting them in your application
type Adapter struct {
// Pull fucntion will be where secrets will be retrieved and will return a EnvMap
Pull func() (*Map, error)
}
var (
envFileNames = []string{".env"}
requiredKeys []string
adapters []*Adapter
)
/* Load scans one or mores that are given and exports the vairbles in the file if they do not exist.
if a file is not provided then the `.env` file in the current working directory will be scaned
instead if one was found.
After that happens load will run the adapters if any were provided then it will run thos adapters
to return a env map that will be exported as well
*/
func Load(filenames ...string) error {
if len(filenames) == 0 {
filenames = envFileNames
}
// load files
files, err := loadFiles(false, filenames...)
if err != nil {
return err
}
globalEnvMap := NewMap()
// parse files
for _, content := range files {
// parse file
emap := Parse(content)
globalEnvMap.SetMap(emap)
}
if len(adapters) != 0 {
// run pull secrets from adapters
for _, adapter := range adapters {
// pulling secrets
emap, err := adapter.Pull()
if err != nil {
return fmt.Errorf("error occured running adapter: %s", err)
}
// set adapters EnvMap to global EnvMap
globalEnvMap.SetMap(emap)
}
}
// set env map to env
err = setEnvMap(globalEnvMap)
if err != nil {
return err
}
return nil
}
/* Load scans one or mores that are given and exports the vairbles in the file if they do not exist.
if a file is not provided then the `.env` file in the current working directory will be scaned
instead if one was found.
After that happens load will run the adapters if any were provided then it will run thos adapters
to return a env map that will be exported as well.
This will error if a required key/s are missing if require keys were provided
*/
func MustLoad(filenames ...string) error {
err := Load(filenames...)
if err != nil {
return err
}
// check for missing required keys
if len(requiredKeys) != 0 {
var missingKeys []string
for _, key := range requiredKeys {
val, ok := os.LookupEnv(key)
if !ok && val == "" {
missingKeys = append(missingKeys, key)
}
}
if len(missingKeys) != 0 {
return fmt.Errorf("Required keys missing or empty: %s", missingKeys)
}
}
return nil
}
// LoadSecrets will run all your adapters and set all the env vars that were fetch then set them to your env in your application
func LoadSecrets() error {
globalEnvMap := NewMap()
if len(adapters) != 0 {
// run pull secrets from adapters
for _, adapter := range adapters {
// pulling secrets
emap, err := adapter.Pull()
if err != nil {
return fmt.Errorf("error occured running adapter: %s", err)
}
// set adapters EnvMap to global EnvMap
globalEnvMap.SetMap(emap)
}
}
// set env map to env
err := setEnvMap(globalEnvMap)
if err != nil {
return err
}
return nil
}
/* Must LoadSecrets will run all your adapters and set all the env vars that were fetch then set them to your env in your application.
As well as checking for required secrets */
func MustLoadSecrets() error {
err := LoadSecrets()
if err != nil {
return err
}
// check for missing required keys
if len(requiredKeys) != 0 {
var missingKeys []string
for _, key := range requiredKeys {
val, ok := os.LookupEnv(key)
if !ok && val == "" {
missingKeys = append(missingKeys, key)
}
}
if len(missingKeys) != 0 {
return fmt.Errorf("Required keys missing or empty: %s", missingKeys)
}
}
return nil
}
// RequiredKeys is a way for you to set a checkpoint when loading secrets or required exported variables for your application
func RequiredKeys(keys []string) {
requiredKeys = append(requiredKeys, keys...)
}
// ApplyAdapter will set middleware, when Load or MustLoad is called those middleware will be called
func ApplyAdapter(a ...*Adapter) {
adapters = append(adapters, a...)
}
// helper functions
func loadFiles(strict bool, filenames ...string) ([]string, error) {
var files []string
for _, filename := range filenames {
f, err := os.Stat(filename)
if err != nil {
fmt.Printf("could not load %s: %s\n", filename, err)
continue
}
if f.IsDir() {
fmt.Printf("Could not load %s: %s", f.Name(), err)
continue
}
bytes, err := ioutil.ReadFile(f.Name())
if err != nil {
return files, nil
}
files = append(files, string(bytes))
}
return files, nil
}
func setEnvMap(target *Map) error {
for key, val := range target.Map {
err := os.Setenv(key, val)
if err != nil {
return err
}
}
return nil
}
// Parse takes a io.Reader that will parsed and returns a env map
func Parse(content string) *Map {
emap := NewMap()
lines := strings.Split(content, "\n")
for _, line := range lines {
line = strings.Trim(line, " ")
if !strings.HasPrefix(line, "#") && line != "" {
key, val := parseLine(line)
emap.Set(key, val)
}
}
return emap
}
func parseLine(line string) (string, string) {
splitLine := strings.SplitN(line, "=", 2)
return splitLine[0], splitLine[1]
}