2

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.

0

1 Answer 1

10

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 }}

`)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.