kelseyhightower / envconfig

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

[Feature] Custom Decoders #3

Closed adrianduke closed 8 years ago

adrianduke commented 10 years ago

So I needed to implement an additional config provider for my app via env vars and stumbled across this short and sweet library, but I needed a little extra in the form of custom decoding of the env var value itself (think slices of data or even references to other env vars).

In my particular case I had a variable number of hashes I needed to get into my app as a single struct field and couldn't find a way to do it easily with the current code base so I extended it with the concept of custom decoders.

Effectively you register a decoder for a field name before you call Process(), you can register as many decoders as you like and you can also clear them out once you finish (as the storage mechanism is a package level var):

     type Config struct {
         Keys []string
     }

     envconfig.RegisterDecoder("Keys", func(value string, fieldValue, struc reflect.Value) error {
         ...logic...
     })
     defer envconfig.ClearDecoders()

In this case it is registered to the Keys struct field. You are given access to the current env var value, struct field and the struct being operated on. This should allow for maximum flexibility for a custom decoder.

The decoder func could be turned into a named type but I thought it was shorter for the caller to use an anonymous func. This can be changed though.

Thanks, Adrian

adrianduke commented 10 years ago

Looks like it failed due to a discrepancy between go1.1 and go1.3 fmt formatting, I'll see if I can fix it

kelseyhightower commented 10 years ago

@adrianduke This looks pretty nice. Any change of getting the test to pass?

adrianduke commented 10 years ago

@kelseyhightower sorry been busy at work, will get a fix for this asap.

adrianduke commented 9 years ago

I have updated this PR to support 1.1 (issue was due to indexed fmt arguments, which were introduced in 1.2)... I also added more go versions to the travis build (1.1, 1.2, 1.3 & tip) as they were missing. I can take them out of this PR if you prefer a separate PR for it.

-EDIT-

Apologies it took so long!

teepark commented 8 years ago

This is great -- could we follow the stdlib's lead and let receiver types handle their own decoding? We'd supply an interface, and if a receiver implements it, we'd use that for the decoding (like json or sql). Then we could avoid maintaining a registry, with the deferred clearing and all that.

teepark commented 8 years ago

35 addresses this now with a Decoder interface.