Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Option to require env vars to be set and not empty by default #344

Open
arvenil opened this issue Nov 20, 2024 · 2 comments
Open

Option to require env vars to be set and not empty by default #344

arvenil opened this issue Nov 20, 2024 · 2 comments

Comments

@arvenil
Copy link

arvenil commented Nov 20, 2024

It looks like there is no way to require env vars to be set and not empty by default?

https://go.dev/play/p/fiRtVlFW3if

package main

import (
	"fmt"

	"github.com/caarlos0/env/v10"
)

func main() {
	type Config struct {
		Username string `env:"EX_USERNAME" envDefault:"admin"`
		Password string `env:"EX_PASSWORD"`
	}

	var cfg Config
	if err := env.ParseWithOptions(&cfg, env.Options{
		Environment: map[string]string{
			"EX_USERNAME": "https://google.com",
			"EX_PASSWORD": "",
		},
		RequiredIfNoDef: true,
	}); err != nil {
		fmt.Println(err)
	}

	fmt.Printf("%+v\n", cfg)
}

Results in

{Username:https://google.com Password:}

Program exited.
@caarlos0
Copy link
Owner

you can append ,notEmpty to the env name, e.g.:

	type Config struct {
		Username string `env:"EX_USERNAME" envDefault:"admin"`
		Password string `env:"EX_PASSWORD,notEmpty"`
	}

https://pkg.go.dev/github.com/caarlos0/env/v11#example-Parse-NotEmpty

@arvenil
Copy link
Author

arvenil commented Nov 20, 2024

Yes, but that forces us to remember to append it to every field. We tend to forget set the value and program instead of failing on initialization often fails when the value is finally needed. The idea is the same as RequiredIfNoDef but extended to empty variables.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants