登录
首页 >  Golang >  Go问答

在 Go 中如何在多行字符串中插入变量?

来源:stackoverflow

时间:2024-03-15 22:51:28 388浏览 收藏

Go 中无法直接在多行字符串中插入变量。但可以使用 `fmt.Sprintf` 或 `text/template` 包实现类似效果。`fmt.Sprintf` 可使用格式化字符串插入变量,而 `text/template` 提供更强大的模板功能,支持条件语句和循环等。

问题内容

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

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)

正确答案


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

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

今天关于《在 Go 中如何在多行字符串中插入变量?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>