github.com/annwntech/go-micro/v2@v2.9.5/config/source/env/options.go (about)

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