简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM