How to insert a variable in to a multiline (backtick) string in Go?

huangapple go评论88阅读模式
英文:

How to insert a variable in to a multiline (backtick) string in Go?

问题

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

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)
英文:

I am trying to insert a variable in to a string that I pass in to a byte array. What I want is something like this:

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

I know that's not possible in Go as I've taken that from JS, but I would like to do something like that.


Working with @TheFool's answer I have done this:

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

答案1

得分: 6

你可以使用任何类型的printf函数,例如Sprintf。

package main

import "fmt"

func main() {
	myLocation := "foobar123"
	rawJSON := []byte(`{
	"level": "debug",
	"encoding": "json",
	// ... other stuff
	"initialFields": { "location": "%s" }
}`)
    // 获取格式化后的字符串
	s := fmt.Sprintf(string(rawJSON), myLocation)
    // 以某种方式使用该字符串,例如打印出来
	fmt.Println(s) 
}

对于更复杂的模板,你还可以使用模板包(templates package)。使用模板包,你可以使用一些函数和其他类型的表达式,类似于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模板包。

英文:

You can use any kind of printf. For example 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) 
}

For more complex templates, you can also use the templates package. With that you can use some functions and other kinds of expressions, similar to something like 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())
}

Note, that there are 2 different templates packages html/template and text/template. The html one is stricter, for safety purposes. If you get the input from untrusted sources, it's probably wise to opt for the html one.

huangapple
  • 本文由 发表于 2021年12月17日 04:42:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/70385373.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定