Skip to content

Commit

Permalink
required tag needed to support prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
rayjlinden committed Feb 13, 2019
1 parent 735b9c1 commit c104dc9
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
6 changes: 3 additions & 3 deletions env.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ func get(field reflect.StructField, prefix string) (string, error) {
case "":
break
case "required":
val, err = getRequired(key)
val, err = getRequired(key, prefix)
default:
err = fmt.Errorf("env tag option %q not supported", opt)
}
Expand All @@ -184,8 +184,8 @@ func parseKeyForOption(key string) (string, []string) {
return opts[0], opts[1:]
}

func getRequired(key string) (string, error) {
if value, ok := os.LookupEnv(key); ok {
func getRequired(key, prefix string) (string, error) {
if value, ok := os.LookupEnv(prefix + key); ok {
return value, nil
}
return "", fmt.Errorf("required environment variable %q is not set", key)
Expand Down
14 changes: 14 additions & 0 deletions env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,20 @@ func TestNoErrorRequiredSet(t *testing.T) {
assert.Equal(t, "val", cfg.IsRequired)
}

func TestNoErrorRequiredSetWithPrefix(t *testing.T) {
type config struct {
IsRequired string `env:"IS_REQUIRED,required"`
}

cfg := &config{}

os.Setenv("CLIENT_IS_REQUIRED", "val")
defer os.Clearenv()
assert.NoError(t, ParseWithPrefix(cfg, "CLIENT_"))
assert.Equal(t, "val", cfg.IsRequired)
}


func TestErrorRequiredNotSet(t *testing.T) {
type config struct {
IsRequired string `env:"IS_REQUIRED,required"`
Expand Down

0 comments on commit c104dc9

Please sign in to comment.