Go字符串模板替换

如果要在Go语言中做字符串模板替换,比如配置模板实例化,你会如何做呢?

fmt.Sprintf大概率是多数人首先想到的方式,但今天我们的主角是os.Expand

先来个栗子开胃。

var config = `
app.name = ${appName}
app.ip = ${appIP}
app.port = ${appPort}
`

var dev = map[string]string{
	"appName": "my_app",
	"appIP":   "0.0.0.0",
	"appPort": "8080",
}

func main() {
	s := os.Expand(config, func(k string) string { return dev[k] })
	fmt.Println(s)
}

/**output**

app.name = my_app
app.ip = 0.0.0.0
app.port = 8080
*/

如果仅仅是介绍os.Expand的使用,那么本文到这里就可以结束了。然而我并不打算在这里结束,因为还有两个疑问:

  1. 为什么占位符是${xxx}
  2. 占位符只能是${xxx}吗?

让我们带着这两个疑问,进入源码一探究竟。

os.Expand1的源码非常简单,下面是源码的全部内容。

// Expand根据mapping函数替换字符串中的${var}或$var
// 例如, os.ExpandEnv(s)等价于os.Expand(s, os.Getenv)
func Expand(s string, mapping func(string) string) string {
	var buf []byte
	// ${} is all ASCII, so bytes are fine for this operation.
	i := 0
	for j := 0; j < len(s); j++ {
		if s[j] == '$' && j+1 < len(s) {
			if buf == nil {
				buf = make([]byte, 0, 2*len(s))
			}
			buf = append(buf, s[i:j]...)
			name, w := getShellName(s[j+1:])
			if name == "" && w > 0 {
				// Encountered invalid syntax; eat the
				// characters.
			} else if name == "" {
				// Valid syntax, but $ was not followed by a
				// name. Leave the dollar character untouched.
				buf = append(buf, s[j])
			} else {
				buf = append(buf, mapping(name)...)
			}
			j += w
			i = j + 1
		}
	}
	if buf == nil {
		return s
	}
	return string(buf) + s[i:]
}

从注释我们可以看到,占位符中的{}是可以省略的,后面我们会看到它是如何实现的。

buf用来存放替换过程中生成的字符串,初始化时会预分配两倍的容量。看到这里你会发现这并不是一个高效的实现方式,其实不太适合大规模频繁的模板替换场景。不过一般情况下配置模板不会特别大,更不会频繁替换,所以还是可以放心大胆的用的。

变量i是当前字符(更准确的说是字节)的下标,然后就开始搜索字符串中的$关键字,如果找到了,就会通过一个叫getShellName2的函数拿到配置名和长度(包括{}),它的源码如下。

// getShellName returns the name that begins the string and the number of bytes
// consumed to extract it. If the name is enclosed in {}, it's part of a ${}
// expansion and two more bytes are needed than the length of the name.
func getShellName(s string) (string, int) {
	switch {
	case s[0] == '{':
		if len(s) > 2 && isShellSpecialVar(s[1]) && s[2] == '}' {
			return s[1:2], 3
		}
		// Scan to closing brace
		for i := 1; i < len(s); i++ {
			if s[i] == '}' {
				if i == 1 {
					return "", 2 // Bad syntax; eat "${}"
				}
				return s[1:i], i + 1
			}
		}
		return "", 1 // Bad syntax; eat "${"
	case isShellSpecialVar(s[0]):
		return s[0:1], 1
	}
	// Scan alphanumerics.
	var i int
	for i = 0; i < len(s) && isAlphaNum(s[i]); i++ {
	}
	return s[:i], i
}

// isShellSpecialVar reports whether the character identifies a special
// shell variable such as $*.
func isShellSpecialVar(c uint8) bool {
	switch c {
	case '*', '#', '$', '@', '!', '?', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
		return true
	}
	return false
}

// isAlphaNum reports whether the byte is an ASCII letter, number, or underscore
func isAlphaNum(c uint8) bool {
	return c == '_' || '0' <= c && c <= '9' || 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z'
}

getShellName对名称的解析有3中情况:

  1. ${xxx},其中x是任意字符
  2. $x,其中x是特殊终端字符
  3. $xxx,其中x是字母数字或下划线

第一种情况是最常用的,它对名称没什么限制,适用范围广,对人友好。

第二种情况有没有坑呢?如果你想用数字作为名称的话,它只能支持0~9十个名称,$12$1并无区别。

第三种情况不能以数字开头,因为情况2的优先级更高;其次占位符之间不能用下划线分隔,比如$name_$id替换的结果可能并不像你想象的那样,此时应该用${name}_${id}


  1. src/os/env.go#16 ↩︎

  2. src/os/env.go#72 ↩︎

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值