anthdm / superkit

MIT License
1.03k stars 88 forks source link

Validation for env variables #9

Closed Oudwins closed 5 months ago

Oudwins commented 5 months ago

Hey!

I was watching one of your streams the other day you were playing around with environment variables. I had an idea for a simple validation api that I think could be quite nice for them. Its inspired by what T3.gg does.

I have a working example by extending the validation library, I'm happy to contribute a PR but wanted to first make sure its something you like for the vision of the project.

The idea is to have a global Env struct with all the environment variables and validation for them. With this we achieve:

  1. Auto complete when using env variables
  2. Crashing the program on startup if environment variables are missing

This is what the API would look like:

var Env = struct {
    SUPERKIT_ENV     string
    HTTP_LISTEN_ADDR string
    DB_URL           string
    // ...
}{
    SUPERKIT_ENV:     v.Env("SUPERKIT_ENV", v.Required, v.In([]string{"development", "production"})).Validate(),
    HTTP_LISTEN_ADDR: v.Env("HTTP_LISTEN_ADDR", v.Min(3)).Default("3000").Validate(),
    DB_URL:           v.Env("DB_URL", v.Required, v.URL).Validate(),
}

There is still a little wackiness with the api since you can pass v.Required and then .default() together which is weird.

I also think there is space to somehow convert env variables into things that are not strings in this step. For example for a server you might have a max connections env variable that is actually an int (since os.Getenv always returns a string)

anthdm commented 5 months ago

@Oudwins I like this idea! Would be cool to see a draft of this. Thanks for sharing this idea.

Oudwins commented 5 months ago

@anthdm closing this since I opened the draft