go-micro.dev/v5@v5.12.0/config/source/env/options.go (about)

     1  package env
     2  
     3  import (
     4  	"context"
     5  	"strings"
     6  
     7  	"go-micro.dev/v5/config/source"
     8  )
     9  
    10  type strippedPrefixKey struct{}
    11  type prefixKey struct{}
    12  
    13  // WithStrippedPrefix sets the environment variable prefixes to scope to.
    14  // These prefixes will be removed from the actual config entries.
    15  func WithStrippedPrefix(p ...string) source.Option {
    16  	return func(o *source.Options) {
    17  		if o.Context == nil {
    18  			o.Context = context.Background()
    19  		}
    20  
    21  		o.Context = context.WithValue(o.Context, strippedPrefixKey{}, appendUnderscore(p))
    22  	}
    23  }
    24  
    25  // WithPrefix sets the environment variable prefixes to scope to.
    26  // These prefixes will not be removed. Each prefix will be considered a top level config entry.
    27  func WithPrefix(p ...string) source.Option {
    28  	return func(o *source.Options) {
    29  		if o.Context == nil {
    30  			o.Context = context.Background()
    31  		}
    32  		o.Context = context.WithValue(o.Context, prefixKey{}, appendUnderscore(p))
    33  	}
    34  }
    35  
    36  func appendUnderscore(prefixes []string) []string {
    37  	//nolint:prealloc
    38  	var result []string
    39  	for _, p := range prefixes {
    40  		if !strings.HasSuffix(p, "_") {
    41  			result = append(result, p+"_")
    42  			continue
    43  		}
    44  
    45  		result = append(result, p)
    46  	}
    47  
    48  	return result
    49  }