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

Ala*_*anH 4 arrays string go template-literals

我试图将变量插入到传递给字节数组的字符串中。我想要的是这样的:

myLocation := "foobar123"
rawJSON := []byte(`{
        "level": "debug",
        "encoding": "json",
        // ... other stuff
        "initialFields": {"location": ${myLocation} },
    }`)
Run Code Online (Sandbox Code Playgroud)

我知道这在 Go 中是不可能的,因为我是从 JS 那里得到的,但我想做类似的事情。


根据@TheFool的回答,我已经这样做了:

    config := fmt.Sprintf(`{
        "level": "debug",
        "encoding": "json",
        "initialFields": {"loggerLocation": %s },
    }`, loggerLocation)
    rawJSON := []byte(config)
Run Code Online (Sandbox Code Playgroud)

The*_*ool 8

您可以使用任何类型的 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) 
}
Run Code Online (Sandbox Code Playgroud)

对于更复杂的模板,您还可以使用 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())
}
Run Code Online (Sandbox Code Playgroud)

请注意,有 2 个不同的模板包html/templatetext/template. 出于安全目的,html 更为严格。如果您从不受信任的来源获取输入,那么选择 html 可能是明智的选择。

  • @TheRealFakeNews `fmt.Sprintf` 不打印任何内容,它返回一个字符串。 (2认同)