kelseyhightower / envconfig

Golang library for managing configuration data from environment variables
MIT License
5.01k stars 377 forks source link

MustProcessT: return the typed spec #213

Closed imjasonh closed 2 months ago

imjasonh commented 2 months ago

This adds a generic MustProcessT method, that panics if processing fails, and returns the spec value.

Example usage:

package main

import (
  "log"

  "github.com/kelseyhightower/envconfig"
)

env := envconfig.MustProcessT("", &struct{
  Foo string `envconfig:"FOO" required:"true"`
}{})

func main() {
  log.Println("your FOO is " + env.Foo)
}

This lets the env struct be moved to an init-time var, out of func main, and retains all the env parsing behavior we've all come to know and love.

The structure of that var statement is kind of gross (inline-defining a struct and its empty value, and passing it to the method), if I'm missing some way to make it better, let me know.

Type parameters were required, since MustProcessT(string, interface{}) interface{} loses information about the input type. You could cast back to the type you want, but generics are better IMO, since it lets you do it all in one statement.

This change requires go.mod to state the version of Go that's needed. Otherwise, go build defaults to an old version, which doesn't have type parameters:

go build ./...
# github.com/kelseyhightower/envconfig
./envconfig.go:238:19: type parameter requires go1.18 or later (-lang was set to go1.16; check go.mod)
./envconfig.go:238:21: predeclared any requires go1.18 or later (-lang was set to go1.16; check go.mod)

I chose the latest Go, but if you think it should be 1.18 I'm fine with that too.