gonfig.GetEnvStrWithDefault   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nop 2
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
package gonfig
2
3
import (
4
	"flag"
5
	"log"
6
	"os"
7
	"strconv"
8
	"strings"
9
	"sync"
10
11
	"github.com/joho/godotenv"
12
)
13
14
var configurator sync.Once
15
16
// GetEnv returns ENV variable from environment or .env file as []byte if it's possible and ENV variable exists
17
// Default 0
18
func GetEnv(key string) []byte {
19
	configurator.Do(func() {
20
		_ = godotenv.Load()
21
	})
22
	return []byte(os.Getenv(key))
23
}
24
25
// GetEnvStr returns ENV variable from environment or .env file as string if it's possible and ENV variable exists
26
// Default ""
27
func GetEnvStr(key string) string {
28
	return string(GetEnv(key))
29
}
30
31
// GetEnvArrStr returns ENV variable from environment or .env file as []string if it's possible and ENV variable exists
32
// Default ""
33
func GetEnvArrStr(key string) []string {
34
	str := string(GetEnv(key))
35
	if str == "" {
36
		return nil
37
	}
38
	return strings.Split(str, ";")
39
}
40
41
// GetEnvStrWithDefault returns ENV variable from environment or .env file as string else returns default value
42
func GetEnvStrWithDefault(key string, defaultValue string) string {
43
	if value := string(GetEnv(key)); value != "" {
44
		return value
45
	}
46
	return defaultValue
47
}
48
49
// GetEnvInt returns ENV variable from environment or .env file as int if it's possible and ENV variable exists
50
// Default 0
51
func GetEnvInt(key string) int {
52
	result, err := strconv.Atoi(GetEnvStr(key))
53
	if err != nil {
54
		log.Println(err)
55
	}
56
	return result
57
}
58
59
// GetEnvIntWithDefault returns ENV variable from environment or .env file as int else returns default value
60
func GetEnvIntWithDefault(key string, defaultValue int) int {
61
	if result, err := strconv.Atoi(GetEnvStr(key)); err == nil {
62
		return result
63
	}
64
	return defaultValue
65
}
66
67
// GetListenPort returns a flag to the port to launch the application.
68
// Looks at the PORT environment variable if the application is running without a flag.
69
// Default 80
70
func GetListenPort() *string {
71
	port := "80"
72
	if envPort := GetEnvStr("PORT"); envPort != "" {
73
		port = envPort
74
	}
75
	return flag.String("port", port, "Example: -port=8080")
76
}
77
78
//GetApplicationMode returns the flag to the application launch mode.
79
// Looks at the APP_MODE environment variable if the application is running without a flag -mode
80
// Default release
81
func GetApplicationMode() *string {
82
	mode := "release"
83
	if envMode := GetEnvStr("APP_MODE"); envMode != "" {
84
		mode = envMode
85
	}
86
	return flag.String("mode", mode, "Example: -mode=debug")
87
}
88