| 1 | Babyenv |
| 2 | ======= |
| 3 | |
| 4 | [](http://godoc.org/github.com/meowgorithm/babyenv) |
| 5 | |
| 6 | Package babyenv collects environment variables and places them in corresponding |
| 7 | struct fields. It aims to reduce the boilerplate in reading data from the |
| 8 | environment. |
| 9 | |
| 10 | The struct should contain `env` tags indicating the names of corresponding |
| 11 | environment variables. The values of those environment variables will be then |
| 12 | collected and placed into the struct. If nothing is found, struct fields will |
| 13 | be given their default values (for example, `bool`s will be `false`). |
| 14 | |
| 15 | ```go |
| 16 | type config struct { |
| 17 | Name string `env:"NAME"` |
| 18 | } |
| 19 | ``` |
| 20 | |
| 21 | Default values can also be provided in the `default` tag. |
| 22 | |
| 23 | ```go |
| 24 | type config struct { |
| 25 | Name string `env:"NAME" default:"Jane"` |
| 26 | } |
| 27 | ``` |
| 28 | |
| 29 | A 'required' flag can also be set in the following format: |
| 30 | |
| 31 | ```go |
| 32 | type config struct { |
| 33 | Name string `env:"NAME,required"` |
| 34 | } |
| 35 | ``` |
| 36 | |
| 37 | If a required flag is set the 'default' tag will be ignored. |
| 38 | |
| 39 | |
| 40 | ## Example |
| 41 | |
| 42 | ```go |
| 43 | package main |
| 44 | |
| 45 | import ( |
| 46 | "fmt" |
| 47 | "os" |
| 48 | "github.com/meowgorithm/babyenv" |
| 49 | ) |
| 50 | |
| 51 | type config struct { |
| 52 | Debug bool `env:"DEBUG"` |
| 53 | Port string `env:"PORT" default:"8000"` |
| 54 | Workers int `env:"WORKERS" default:"16"` |
| 55 | Name string `env:"NAME,required"` |
| 56 | } |
| 57 | |
| 58 | func main() { |
| 59 | os.Setenv("DEBUG", "true") |
| 60 | os.Setenv("WORKERS", "4") |
| 61 | os.Setenv("NAME", "Jane") |
| 62 | |
| 63 | var cfg config |
| 64 | if err := babyenv.Parse(&cfg); err != nil { |
| 65 | log.Fatalf("could not get environment vars: %v", err) |
| 66 | } |
| 67 | |
| 68 | fmt.Printf("%b\n%s\n%d\n%s", cfg.Debug, cfg.Port, cfg.Workers, cfg.Name) |
| 69 | |
| 70 | // Output: |
| 71 | // true |
| 72 | // 8000 |
| 73 | // 4 |
| 74 | // Jane |
| 75 | } |
| 76 | ``` |
| 77 | |
| 78 | |
| 79 | ## Supported Types |
| 80 | |
| 81 | Currently, only the following types are supported: |
| 82 | |
| 83 | * `string` |
| 84 | * `bool` |
| 85 | * `int` |
| 86 | * `int64` |
| 87 | * `[]byte` |
| 88 | * `*string` |
| 89 | * `*bool` |
| 90 | * `*int` |
| 91 | * `*[]byte` |
| 92 | |
| 93 | Pull requests are welcome, especially for new types. |
| 94 | |
| 95 | |
| 96 | ## Credit |
| 97 | |
| 98 | This is entirely based on the [caarlos0][carlos]’s [env][carlosenv] package. |
| 99 | This one simply has a slightly different interface, and less functionality. |
| 100 | |
| 101 | [carlos]: https://github.com/caarlos0 |
| 102 | [carlosenv]: https://github.com/caarlos0/env |
| 103 | |
| 104 | |
| 105 | ## LICENSE |
| 106 | |
| 107 | MIT |