This repository has been archived by the owner on Jul 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgonfig.go
87 lines (76 loc) · 2.32 KB
/
gonfig.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
package gonfig
import (
"flag"
"log"
"os"
"strconv"
"strings"
"sync"
"github.com/joho/godotenv"
)
var configurator sync.Once
// GetEnv returns ENV variable from environment or .env file as []byte if it's possible and ENV variable exists
// Default 0
func GetEnv(key string) []byte {
configurator.Do(func() {
_ = godotenv.Load()
})
return []byte(os.Getenv(key))
}
// GetEnvStr returns ENV variable from environment or .env file as string if it's possible and ENV variable exists
// Default ""
func GetEnvStr(key string) string {
return string(GetEnv(key))
}
// GetEnvArrStr returns ENV variable from environment or .env file as []string if it's possible and ENV variable exists
// Default ""
func GetEnvArrStr(key string) []string {
str := string(GetEnv(key))
if str == "" {
return nil
}
return strings.Split(str, ";")
}
// GetEnvStrWithDefault returns ENV variable from environment or .env file as string else returns default value
func GetEnvStrWithDefault(key string, defaultValue string) string {
if value := string(GetEnv(key)); value != "" {
return value
}
return defaultValue
}
// GetEnvInt returns ENV variable from environment or .env file as int if it's possible and ENV variable exists
// Default 0
func GetEnvInt(key string) int {
result, err := strconv.Atoi(GetEnvStr(key))
if err != nil {
log.Println(err)
}
return result
}
// GetEnvIntWithDefault returns ENV variable from environment or .env file as int else returns default value
func GetEnvIntWithDefault(key string, defaultValue int) int {
if result, err := strconv.Atoi(GetEnvStr(key)); err == nil {
return result
}
return defaultValue
}
// GetListenPort returns a flag to the port to launch the application.
// Looks at the PORT environment variable if the application is running without a flag.
// Default 80
func GetListenPort() *string {
port := "80"
if envPort := GetEnvStr("PORT"); envPort != "" {
port = envPort
}
return flag.String("port", port, "Example: -port=8080")
}
//GetApplicationMode returns the flag to the application launch mode.
// Looks at the APP_MODE environment variable if the application is running without a flag -mode
// Default release
func GetApplicationMode() *string {
mode := "release"
if envMode := GetEnvStr("APP_MODE"); envMode != "" {
mode = envMode
}
return flag.String("mode", mode, "Example: -mode=debug")
}