Skip to content

Commit

Permalink
genv
Browse files Browse the repository at this point in the history
  • Loading branch information
snail007 committed Jan 8, 2024
1 parent 0771ee6 commit 03243a8
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 0 deletions.
43 changes: 43 additions & 0 deletions util/env/env.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package genv

import (
gvalue "github.com/snail007/gmc/util/value"
"os"
)

// Accessor access to os environment variable with auto prefix support
// and the value is gvalue.AnyValue can be used as many data type
type Accessor struct {
prefix string
}

func NewAccessor(prefix string) *Accessor {
return &Accessor{prefix: prefix}
}

func (s *Accessor) addPrefix(str string) string {
return s.prefix + str
}

func (s *Accessor) Get(key string) *gvalue.AnyValue {
v := os.Getenv(s.addPrefix(key))
return gvalue.NewAny(v)
}

func (s *Accessor) Lookup(key string) (*gvalue.AnyValue, bool) {
v, found := os.LookupEnv(s.addPrefix(key))
if !found {
return nil, false
}
return gvalue.NewAny(v), true
}

func (s *Accessor) Set(key, value string) *Accessor {
os.Setenv(s.addPrefix(key), value)
return s
}

func (s *Accessor) Unset(key string) *Accessor {
os.Unsetenv(s.addPrefix(key))
return s
}
52 changes: 52 additions & 0 deletions util/env/env_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package genv

import (
"github.com/stretchr/testify/assert"
"os"
"testing"
)

func TestAccessor(t *testing.T) {
// Set up test cases
accessor := NewAccessor("PREFIX_")

// Test Get method
key := "KEY"
expectedValue := "value"
os.Setenv("PREFIX_KEY", expectedValue)
result := accessor.Get(key)
if result.String() != expectedValue {
t.Errorf("Get(%s) = %s, want %s", key, result, expectedValue)
}

// Test Lookup method
lookupKey := "LOOKUP_KEY"
lookupExpectedValue := "lookup_value"
os.Setenv("PREFIX_LOOKUP_KEY", lookupExpectedValue)
lookupResult, found := accessor.Lookup(lookupKey)
if !found || lookupResult.String() != lookupExpectedValue {
t.Errorf("Lookup(%s) = %s, found = %t, want %s, true", lookupKey, lookupResult, found, lookupExpectedValue)
}
lookupResult, found = accessor.Lookup(lookupKey + "none")
assert.False(t, found)
assert.Nil(t, lookupResult)

// Test Set method
setKey := "SET_KEY"
setValue := "set_value"
accessor.Set(setKey, setValue)
setResult := os.Getenv("PREFIX_SET_KEY")
if setResult != setValue {
t.Errorf("Set(%s, %s) did not set the environment variable correctly", setKey, setValue)
}

// Test Unset method
unsetKey := "UNSET_KEY"
unsetValue := "unset_value"
os.Setenv("PREFIX_UNSET_KEY", unsetValue)
accessor.Unset(unsetKey)
unsetResult := os.Getenv("PREFIX_UNSET_KEY")
if unsetResult != "" {
t.Errorf("Unset(%s) did not unset the environment variable", unsetKey)
}
}

0 comments on commit 03243a8

Please sign in to comment.