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

MustProcessT: return the typed spec #213

Closed
wants to merge 1 commit into from

Conversation

imjasonh
Copy link

@imjasonh imjasonh commented Jul 3, 2024

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.

Signed-off-by: Jason Hall <jason@chainguard.dev>
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

Successfully merging this pull request may close these issues.

1 participant