placeholder.go 1.8 KB
Newer Older
W
wangzelin.wzl 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
package config

import (
	"os"
	"strings"
)

const (
	DefaultExpanderPrefix = "${"
	DefaultExpanderSuffix = "}"
)

type Expander struct {
	keyValues map[string]string
	replacer  *strings.Replacer
	prefix    string
	suffix    string
}

func (r *Expander) Add(key, value string) {
	r.keyValues[key] = value
	r.replacer = nil
}

func (r *Expander) AddAll(kv map[string]string) {
	for k, v := range kv {
		r.Add(k, v)
	}
}

func (r *Expander) Copy() *Expander {
	if r == nil {
		return nil
	}
	return &Expander{
		prefix:    r.prefix,
		suffix:    r.suffix,
		keyValues: r.keyValues,
		replacer:  r.replacer,
	}
}

func (r *Expander) init() {
	var pairs []string
	for k, v := range r.keyValues {
		pairs = append(pairs, r.prefix+k+r.suffix, v)
	}
	r.replacer = strings.NewReplacer(pairs...)
}

func (r *Expander) Replace(s string) string {
	if r == nil {
		return s
	}
	if r.replacer == nil {
		r.init()
	}
	return r.replacer.Replace(s)
}

func (r *Expander) TrimPrefixSuffix(keys ...string) []string {
	ret := make([]string, 0, len(keys))
	for _, key := range keys {
		ret = append(ret, strings.NewReplacer(r.prefix, "", r.suffix, "").Replace(key))
	}
	return ret
}

func NewExpander(prefix, suffix string) *Expander {
	return NewExpanderWithKeyValues(prefix, suffix, map[string]string{})
}

func NewExpanderWithKeyValues(prefix, suffix string, skvs ...map[string]string) *Expander {
	conkvs := make(map[string]string, 128)
	for _, kvs := range skvs {
		for k, v := range kvs {
			conkvs[k] = v
		}
	}

	return &Expander{
		prefix:    prefix,
		suffix:    suffix,
		keyValues: conkvs,
	}
}

func EnvironKeyValues() map[string]string {
	kvs := make(map[string]string, 64)
	envs := os.Environ()
	for _, pairs := range envs {
		kv := strings.SplitN(pairs, "=", 2)
		kvs[kv[0]] = kv[1]
	}
	return kvs
}