Skip to content

Commit

Permalink
fix: Env variables annotated with file is not allowed to be empty (#109)
Browse files Browse the repository at this point in the history
* adding support to overload env variable and load data from a file

* fixing file perm for TestFile

* refactoring in order to allow file option to act more in accoredence to prior setup

* adding more tests for file option and some extra for requierd option

* updating readme for env file tag

* refactoring to only load value from file if file annotation is given on tag

* updating readme for env file tag

* fixing formating

* fixing type-o

* Update env_test.go

Co-Authored-By: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>

* Update env.go

Co-Authored-By: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>

* lessening requierment for file annotation in order not to enforce that a file has to be given

Co-authored-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>
  • Loading branch information
crholm and caarlos0 authored Feb 26, 2020
1 parent af374f8 commit 8a6889e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
2 changes: 1 addition & 1 deletion env.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ func get(field reflect.StructField) (val string, err error) {
return "", fmt.Errorf(`env: required environment variable %q is not set`, key)
}

if loadFile {
if loadFile && val != "" {
filename := val
val, err = getFromFile(filename)
if err != nil {
Expand Down
37 changes: 36 additions & 1 deletion env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1113,8 +1113,43 @@ func TestFileNoParam(t *testing.T) {
cfg := config{}
err := Parse(&cfg)

assert.NoError(t, err)
}

func TestFileNoParamRequired(t *testing.T) {
type config struct {
SecretKey string `env:"SECRET_KEY,file,required"`
}
defer os.Clearenv()
cfg := config{}
err := Parse(&cfg)

assert.Error(t, err)
assert.EqualError(t, err, "env: required environment variable \"SECRET_KEY\" is not set")
}

func TestFileBadFile(t *testing.T) {
type config struct {
SecretKey string `env:"SECRET_KEY,file"`
}

file, err := ioutil.TempFile("", "sec_key_*")
assert.NoError(t, err)
err = ioutil.WriteFile(file.Name(), []byte("secret"), 0660)
assert.NoError(t, err)

filename := file.Name()
defer os.Clearenv()
os.Setenv("SECRET_KEY", filename)

err = os.Remove(filename)
assert.NoError(t, err)

cfg := config{}
err = Parse(&cfg)

assert.Error(t, err)
assert.EqualError(t, err, `env: could not load content of file "" from variable SECRET_KEY: open : no such file or directory`)
assert.EqualError(t, err, fmt.Sprintf(`env: could not load content of file "%s" from variable SECRET_KEY: open %s: no such file or directory`, filename, filename))
}

func TestFileWithDefault(t *testing.T) {
Expand Down

0 comments on commit 8a6889e

Please sign in to comment.