-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenv.go
88 lines (73 loc) · 1.95 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
// Package env provides a structure for setting and identifying the environment an application is running in.
package env
import (
"log"
"strings"
"sync"
)
// Environment represents the application environment
type Environment string
var (
current Environment // used to optionally track the current env in this package
mu sync.RWMutex // mutex to protect access to current
)
const (
// PROD is the production environment
PROD Environment = "PROD"
// STAGE is the staging environment
STAGE Environment = "STAGE"
// DEV is the development environment
DEV Environment = "DEV"
)
// String returns a human-readable string representation of the Environment
func (e Environment) String() string {
switch e {
case PROD:
return "Production"
case STAGE:
return "Staging"
case DEV:
return "Development"
default:
return "Unknown"
}
}
// IsDev returns true if the Environment is DEV
func (e Environment) IsDev() bool { return e == DEV }
// IsStage returns true if the Environment is STAGE
func (e Environment) IsStage() bool { return e == STAGE }
// IsProd returns true if the Environment is PROD
func (e Environment) IsProd() bool { return e == PROD }
// Parse converts a string to an Environment type
func Parse(env string) Environment {
// Trim spaces and remove quotes
env = strings.TrimSpace(env)
env = strings.Trim(env, `"'`)
// Convert to uppercase and match known environments
switch strings.ToUpper(env) {
case "PROD", "PRODUCTION":
return PROD
case "STAGE", "STAGING":
return STAGE
case "DEV", "DEVELOP", "DEVELOPMENT":
return DEV
default:
log.Printf("Warning: invalid environment '%s', defaulting to PROD", env)
return PROD
}
}
// Set sets the current environment
func Set(env Environment) {
mu.Lock()
defer mu.Unlock()
current = env
}
// Current returns the current environment
func Current() Environment {
mu.RLock()
defer mu.RUnlock()
if current == "" {
return PROD // Default to PROD if not set
}
return current
}