在 Go 中使用模板字符串和函数连接时,会出现错误。例如,将模板字符串与模板函数 b64encode 连接会产生“http://”不是函数的错误。解决方案是使用正确的 JSON 封送处理,确保生成的 JSON 有效且正确转义特殊字符。通过使用 printf 函数扩展模板字符串,可以避免错误,但正确的做法是使用 JSON 封送处理来生成有效的 JSON。
我尝试在 go 函数中模板化一些 json 值,它基本上按照我的预期工作。 但是,如果我尝试将模板字符串与模板函数连接起来,它就会失败(有不同的错误,取决于模板字符串的外观)
例如,我有以下行:
{"application_host":"http://{{ .namespace }}-repo.{{ .namespace }}:3004"}
模板工作并给出以下输出:
{“application_host”:“http://test-repo.test:3004”}
我现在想使用 base64 对值进行编码,并尝试了以下示例:
{"application_host":"{{ http://{{ .namespace }}-repo.{{ .namespace }}:3004 | b64encode }}"}
这给出了错误:
“http://”不是一个函数
如果我只是做类似以下的事情(看起来很可怕):
{"application_host":"{{ printf "http://{{ .namespace }}-repo.{{ .namespace }}:3004"|b64encode }}"}
它输出以下内容:
{"application_host":"ahr0cdovl3t7ic5oqu1fu1bbq0ugfx0tcmvwby57eyautkfnrvnqqunfih19ojmwmdq="}
解码后的内容:
http://{{ .namespace }}-repo.{{ .namespace }}:3004
模板函数目前看起来像这样:
func generateDefinitionJson(filePath string, bodyBytes []byte) (interface{}, error) {
var (
tpl bytes.Buffer
err error
tplInterface, m map[string]interface{}
)
funcMap := template.FuncMap{
// The name "b64encode" is what the function will be called in the template text.
"b64encode": b64encode,
}
// read definition file
fileContent, err := ioutil.ReadFile(filePath)
// load definition as template
t, err := template.New("").Funcs(funcMap).Parse(string(fileContent))
if err != nil {
logger.Error("Parsing Template failed: " + err.Error())
} else {
// create value map
err = json.Unmarshal([]byte(bodyEscaped), &m)
mInterfaceStr := fmt.Sprintf("%v", m)
if err != nil {
logger.Error("Failed to create Value Map: " + err.Error())
} else {
// execute template mapping
err = t.Execute(&tpl, m)
logger.Debug(tpl.String())
if err != nil {
logger.Error("Templating failed: " + err.Error())
}
// unmarshal template into interface
err = json.Unmarshal([]byte(tpl.String()), &tplInterface)
if err != nil {
logger.Error("Couldn't Unmarshal definition to interface: " + err.Error())
}
}
}
return tplInterface, err
}
func b64encode(str string) string {
return base64.StdEncoding.EncodeToString([]byte(str))
}
有人知道如何解决这个问题吗?
解决方案
例如,printf 不会对 {{ .namespace }} 进行模板扩展。相反,它扩展了 %s 和相关动词。这意味着
{"application_host":"{{ printf "http://{{ .namespace }}-repo.{{ .namespace }}:3004"|b64encode }}"}
应该是
{"APPLICATION_HOST":"{{ printf "http://%s-repo.%s:3004" .NAMESPACE .NAMESPACE |b64encode }}"}
但是正确的答案是使用正确的 json 封送处理,这样您就可以确定生成了有效的 json,并且正确转义了任何不寻常的字符,等等。
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
