Skip to content

Commit

Permalink
SetEnv supports envvar and default
Browse files Browse the repository at this point in the history
  • Loading branch information
cristaloleg committed May 25, 2023
1 parent c183998 commit 4b54e20
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 11 deletions.
33 changes: 22 additions & 11 deletions appx.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,34 @@ func Uptime() time.Duration {
}

var (
env string
envOnce sync.Once
appEnv string
appEnvOnce sync.Once
)

// Env returns application environment set via SetEnv func.
func Env() string {
return env
}
// Env where application is running. Can be set via SetEnv func.
func Env() string { return appEnv }

// SetEnv for the application. Can be called once, all next calls panics.
// SetEnv for the application from environment variable or a default.
// Can be called once, all next calls panics.
// Example:
//
// appx.SetEnv("ENV", "dev") // set from ENV or set default "dev"
// appx.SetEnv("ENV", "") // set from ENV or leave unset
// appx.SetEnv("", "dev") // set "dev" directly
//
// This function should be called at the start of the application.
func SetEnv(v string) {
if env != "" {
panic("appx: SetEnv cannot be called twice")
func SetEnv(env, def string) {
if appEnv != "" {
panic("appx: SetEnv called twice")
}

envOnce.Do(func() { env = v })
appEnvOnce.Do(func() {
v := os.Getenv(env)
if v == "" {
v = def
}
appEnv = v
})
}

// OnSignal run fn.
Expand Down
2 changes: 2 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"github.com/cristalhq/appx"
)

func init() { appx.SetEnv("ENV", "dev") }

func main() {
ctx := appx.Context()

Expand Down

0 comments on commit 4b54e20

Please sign in to comment.