Skip to content

Commit

Permalink
feat(env): add Raw method to retrieve environment variable as string
Browse files Browse the repository at this point in the history
Signed-off-by: lvlcn-t <75443136+lvlcn-t@users.noreply.github.com>
  • Loading branch information
lvlcn-t committed Nov 30, 2024
1 parent a58557f commit a4829e1
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
14 changes: 14 additions & 0 deletions env/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ type TypedVariable[T any] interface {
//
// If the environment variable is not set or an error occurs, it either returns preconditioned values and an error or panics if the die flag is set.
Value() (T, error)
// Raw retrieves the environment variable value as a string without converting it to type T.
//
// If the environment variable is not set or an error occurs, it returns the zero value of type T and the error.
Raw() (string, error)
}

// variable represents the builder for an environment variable of type T.
Expand Down Expand Up @@ -193,6 +197,16 @@ func (v *variable[T]) Convert(converter Converter[T]) TypedVariable[T] {
return v
}

// Raw retrieves the environment variable value as a string without converting it to type T.
func (v *variable[T]) Raw() (string, error) {
val, ok := os.LookupEnv(v.key)
if !ok {
_, err := v.handleError(nil)
return "", err
}
return val, nil
}

// Value retrieves the environment variable value.
func (v *variable[T]) Value() (T, error) {
val, ok := os.LookupEnv(v.key)
Expand Down
26 changes: 22 additions & 4 deletions env/env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,10 +209,6 @@ func TestGetWithFallback(t *testing.T) {
}
}

func toPtr[T any](v T) *T {
return &v
}

func TestGet_WithFallback(t *testing.T) {
t.Setenv("TEST_VAR", "123")

Expand Down Expand Up @@ -260,3 +256,25 @@ func TestGet_CustomConverter(t *testing.T) {
t.Errorf("Expected 'converted', got %s", value)
}
}

func TestGet_Raw(t *testing.T) {
t.Setenv("TEST_VAR", "123")

value, err := env.Get[int]("TEST_VAR").NoFallback().Raw()
if err != nil {
t.Errorf("Unexpected error: %v", err)
}

if reflect.TypeOf(value).Kind() != reflect.String {
t.Errorf("Expected string, got %T", value)
}

if value != "123" {
t.Errorf("Expected '123', got %s", value)
}
}

// toPtr returns a pointer to the provided value.
func toPtr[T any](v T) *T {
return &v
}

0 comments on commit a4829e1

Please sign in to comment.