如何在Go语言的多行(反引号)字符串中插入变量?

3
我正在尝试将一个变量插入到我传递给字节数组的字符串中。我想要的是这样的东西:
myLocation := "foobar123"
rawJSON := []byte(`{
        "level": "debug",
        "encoding": "json",
        // ... other stuff
        "initialFields": {"location": ${myLocation} },
    }`)

我知道在Go语言中不可能实现这个,因为我是从JS中学来的,但我想做类似的事情。


参考@TheFool的答案,我已经做到了这一点:

    config := fmt.Sprintf(`{
        "level": "debug",
        "encoding": "json",
        "initialFields": {"loggerLocation": %s },
    }`, loggerLocation)
    rawJSON := []byte(config)
1个回答

7
你可以使用任何类型的 printf。例如 Sprintf。
package main

import "fmt"

func main() {
    myLocation := "foobar123"
    rawJSON := []byte(`{
    "level": "debug",
    "encoding": "json",
    // ... other stuff
    "initialFields": { "location": "%s" },
}`)
    // get the formatted string 
    s := fmt.Sprintf(string(rawJSON), myLocation)
    // use the string in some way, i.e. printing it
    fmt.Println(s) 
}

对于更复杂的模板,您还可以使用 templates 包。使用该包,您可以使用一些函数和其他类型的表达式,类似于 jinja2。

package main

import (
    "bytes"
    "fmt"
    "html/template"
)

type data struct {
    Location string
}

func main() {
    myLocation := "foobar123"
    rawJSON := []byte(`{
    "level": "debug",
    "encoding": "json",
    // ... other stuff
    "initialFields": { "location": "{{ .Location }}" },
}`)

    t := template.Must(template.New("foo").Parse(string(rawJSON)))
    b := new(bytes.Buffer)
    t.Execute(b, data{myLocation})
    fmt.Println(b.String())
}

请注意,有两个不同的模板包html/templatetext/template。其中html模板更为严格,出于安全考虑。如果您从不受信任的来源获取输入,则最好选择html模板。

我并不是想要打印它…那不只对打印有效吗? - TheRealFakeNews
2
fmt.Sprintf 不会打印任何东西,它返回一个字符串。 - JimB
仅供参考,为了准确性,rawJSON是一个字节数组。 - TheRealFakeNews
在调用该函数之前,将其转换为字符串。 s:= string([] byte(“foo”)) - The Fool
@TheFool 我已经更新了我的答案。这样做是否可行?我认为你误解了我的意思。我不需要转换成字符串。 - TheRealFakeNews

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接