Skip to content

Commit

Permalink
Introduce raw literal option
Browse files Browse the repository at this point in the history
  • Loading branch information
rodkevich committed Nov 23, 2024
1 parent e51a54f commit 6a5af6d
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 6 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,20 @@ examples.
}
```

- `default.raw` - sets a literal default value for the environment variable
if it is not set, without applying any transformations or expansions.
This allows for exact values to be used, including special characters.
This option ensures that the exact value provided in the `default.raw` tag is used.

```go
type MyStruct struct {
Token string `env:"TOKEN, default.raw=this^will$be&used|as-is"`
}
```

If the `PORT` environment variable is unset, the field `Port` will be assigned the literal value `expand^makes$no&problems`, without interpreting `$no` or other special characters.


- `prefix` - sets the prefix to use for looking up environment variable keys
on child structs and fields. This is useful for shared configurations:

Expand Down
30 changes: 25 additions & 5 deletions envconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ const (
optPrefix = "prefix="
optRequired = "required"
optSeparator = "separator="
optLiteral = "default.raw="
)

// internalError is a custom error type for errors returned by envconfig.
Expand Down Expand Up @@ -225,6 +226,7 @@ type options struct {
Overwrite bool
DecodeUnset bool
Required bool
Literal bool
}

// Config represent inputs to the envconfig decoding.
Expand Down Expand Up @@ -436,7 +438,7 @@ func processWith(ctx context.Context, c *Config) error {
// Lookup the value, ignoring an error if the key isn't defined. This is
// required for nested structs that don't declare their own `env` keys,
// but have internal fields with an `env` defined.
val, found, usedDefault, err := lookup(key, required, opts.Default, l)
val, found, usedDefault, err := lookup(key, required, opts.Default, opts.Literal, l)
if err != nil && !errors.Is(err, ErrMissingKey) {
return fmt.Errorf("%s: %w", tf.Name, err)
}
Expand Down Expand Up @@ -491,7 +493,7 @@ func processWith(ctx context.Context, c *Config) error {
continue
}

val, found, usedDefault, err := lookup(key, required, opts.Default, l)
val, found, usedDefault, err := lookup(key, required, opts.Default, opts.Literal, l)
if err != nil {
return fmt.Errorf("%s: %w", tf.Name, err)
}
Expand Down Expand Up @@ -581,9 +583,15 @@ LOOP:
opts.Delimiter = strings.TrimPrefix(o, optDelimiter)
case strings.HasPrefix(search, optSeparator):
opts.Separator = strings.TrimPrefix(o, optSeparator)
case strings.HasPrefix(search, optLiteral):
opts.Literal = true
o = strings.TrimLeft(strings.Join(tagOpts[i:], ","), " ")
// Use opts.Default for the literal value. No need for a new string option.
opts.Default = strings.TrimPrefix(o, optDefault)
break LOOP
case strings.HasPrefix(search, optDefault):
// If a default value was given, assume everything after is the provided
// value, including comma-seprated items.
// value, including comma-separated items.
o = strings.TrimLeft(strings.Join(tagOpts[i:], ","), " ")
opts.Default = strings.TrimPrefix(o, optDefault)
break LOOP
Expand All @@ -599,7 +607,7 @@ LOOP:
// first boolean parameter indicates whether the value was found in the
// lookuper. The second boolean parameter indicates whether the default value
// was used.
func lookup(key string, required bool, defaultValue string, l Lookuper) (string, bool, bool, error) {
func lookup(key string, required bool, defaultValue string, literal bool, l Lookuper) (string, bool, bool, error) {
if key == "" {
// The struct has something like `env:",required"`, which is likely a
// mistake. We could try to infer the envvar from the field name, but that
Expand All @@ -624,7 +632,19 @@ func lookup(key string, required bool, defaultValue string, l Lookuper) (string,
}

if defaultValue != "" {
// Expand the default value. This allows for a default value that maps to
if literal {
// If the "literal" option is set, the default value is treated as-is
// without any modification or expansion. This allows for exact values
// to be used, including special characters or reserved formatting.
// Here, we check if the defaultValue contains the literal prefix and
// extract the portion after the prefix.
parts := strings.Split(defaultValue, optLiteral)
if len(parts) > 1 {
return parts[1], false, true, nil
}
}
// If literal option is not set, we can expand the default value.
// This allows for a default value that maps to
// a different environment variable.
val = os.Expand(defaultValue, func(i string) string {
lookuper := l
Expand Down
10 changes: 9 additions & 1 deletion envconfig_doc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,9 @@ func Example_defaults() {

type MyStruct struct {
Port int `env:"PORT, default=8080"`
Username string `env:"USERNAME, default=$OTHER_ENV"`
Username string `env:"USERNAME, default=$OTHER_ENV"` // expands to empty
ApiKey string `env:"API_KEY, default=expand^makes$no&problems"` // $no expands to empty without .raw
Secret string `env:"SECRET, default.raw=expand^makes$no&problems|i,hope|!@#$%^&*()_+~{}[]:;,.<>?/|\\"`
}

var s MyStruct
Expand All @@ -119,9 +121,15 @@ func Example_defaults() {
}

fmt.Printf("port: %d\n", s.Port)
fmt.Printf("username: [%s]\n", s.Username) // for empty brackets
fmt.Printf("api-key: %s\n", s.ApiKey)
fmt.Printf("secret: %s\n", s.Secret)

// Output:
// port: 8080
// username: []
// api-key: expand^makes&problems
// secret: expand^makes$no&problems|i,hope|!@#$%^&*()_+~{}[]:;,.<>?/|\
}

func Example_prefix() {
Expand Down

0 comments on commit 6a5af6d

Please sign in to comment.