-
Notifications
You must be signed in to change notification settings - Fork 135
Expand file tree
/
Copy pathenvironment.go
More file actions
98 lines (78 loc) · 2.21 KB
/
environment.go
File metadata and controls
98 lines (78 loc) · 2.21 KB
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
package environment
import (
"errors"
"log"
"os"
"path/filepath"
"github.com/joho/godotenv"
)
const (
envFileDevelopment = ".env.development"
envFileProduction = ".env.production"
defaultFrontendPath = "./web/build"
)
var errNoBuildDirectory = errors.New("build directory does not exist, run `npm install` and `npm run build` in the web directory")
func LoadEnvironmentVariables() {
if err := loadConfigs(); err != nil {
if errors.Is(err, errNoBuildDirectory) {
log.Fatal("Environment:", err)
}
log.Println("Environment: Failed to find config in CWD, changing CWD to executable path")
executablePath, executableErr := os.Executable()
if executableErr != nil {
log.Fatal("Environment:", executableErr)
}
if chdirErr := os.Chdir(filepath.Dir(executablePath)); chdirErr != nil {
log.Fatal("Environment:", chdirErr)
}
if retryErr := loadConfigs(); retryErr != nil {
log.Fatal("Environment:", retryErr)
}
}
setDefaultEnvironmentVariables()
}
func loadConfigs() error {
if os.Getenv(appEnv) == "development" {
return loadOptionalEnvironmentFile(envFileDevelopment)
}
if err := loadOptionalEnvironmentFile(envFileProduction); err != nil {
return err
}
if os.Getenv(FrontendDisabled) == "" {
if _, err := os.Stat(GetFrontendPath()); os.IsNotExist(err) {
return errNoBuildDirectory
} else if err != nil {
return err
}
}
return nil
}
func loadOptionalEnvironmentFile(fileName string) error {
if _, err := os.Stat(fileName); errors.Is(err, os.ErrNotExist) {
log.Printf("Environment: `%s` not found, continuing with system environment", fileName)
return nil
} else if err != nil {
return err
}
log.Println("Environment: Loading `" + fileName + "`")
if err := godotenv.Load(fileName); err != nil {
return err
}
return nil
}
func GetFrontendPath() string {
frontendPath := os.Getenv(frontendPath)
if frontendPath == "" {
return defaultFrontendPath
}
return frontendPath
}
func setDefaultEnvironmentVariables() {
if os.Getenv(StreamProfilePath) == "" {
log.Println("Environment: Setting STREAM_PROFILE_PATH: profiles")
err := os.Setenv(StreamProfilePath, "profiles")
if err != nil {
log.Panic("Error setting default value for STREAM_PROFILE_PATH")
}
}
}