Skip to content

Commit

Permalink
add Has helper and simplify the Is helper
Browse files Browse the repository at this point in the history
  • Loading branch information
ysmood committed Jan 29, 2024
1 parent f2501a8 commit 25a503b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 17 deletions.
20 changes: 7 additions & 13 deletions goe.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
package goe

import (
"bytes"
"encoding/base64"
"fmt"
"os"
Expand Down Expand Up @@ -100,20 +99,15 @@ type EnvKeyType interface {
}

// Is checks if the env var with the name is equal to the val.
// If the env var is not found, it will return false.
func Is[T EnvType](name string, val T) bool {
if _, has := os.LookupEnv(name); !has {
return false
}

a := any(Require[T](name))
b := any(val)
func Is(name string, val string) bool {
return Get(name, "") == val
}

if _, ok := a.([]byte); ok {
return bytes.Equal(a.([]byte), b.([]byte))
}
// Has checks if the env var with the name exists.
func Has(name string) bool {
_, has := os.LookupEnv(name)

return a == b
return has
}

// Get env var with the name. It will return the defaultVal if it's not found.
Expand Down
24 changes: 20 additions & 4 deletions goe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,6 @@ func TestGet(t *testing.T) {
t.Setenv("DURATION", "1m")
t.Setenv("TIME", "2023-12-21T15:41:51+08:00")

g.True(goe.Is("ENV", "dev"))
g.False(goe.Is("ENV", "stg"))
g.False(goe.Is("NOT_EXISTS", "dev"))

type MyInt int

g.Eq(goe.Get("NUM", MyInt(0)), 2)
Expand Down Expand Up @@ -69,6 +65,26 @@ func TestGet(t *testing.T) {
}).(error).Error(), `failed to parse int: strconv.ParseInt: parsing "xxx": invalid syntax`)
}

func TestIs(t *testing.T) {
g := got.T(t)

t.Setenv("ENV", "dev")

g.True(goe.Is("ENV", "dev"))
g.False(goe.Is("ENV", "stg"))
g.False(goe.Is("NOT_EXISTS", "dev"))
g.True(goe.Is("NOT_EXISTS", ""))
}

func TestHas(t *testing.T) {
g := got.T(t)

t.Setenv("ENV", "dev")

g.True(goe.Has("ENV"))
g.False(goe.Has("NOT_EXISTS"))
}

func TestLoad(t *testing.T) {
g := got.T(t)

Expand Down

0 comments on commit 25a503b

Please sign in to comment.