In a Go template, how can I convert a byte array to a string? One the context values I'm accessing looks like this when I print it:
[34 102 111 111 34]
This corresponds to "foo".
When I print the type of the value (by doing printf "%T" .MyValue), I see json.RawMessage, which is a []byte.
You can use the builtin printf template function and the %s verb.
{{ printf "%s" .MyValue }}
You can also add your own function if you want to avoid printf for some reason.
t, err := template.New("t").Funcs(template.FuncMap{
"btoa": func(b []byte) string { return string(b) },
}).Parse(`
{{ btoa .MyValue }}
`)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With