1
0

options.go 1.2 KB

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