user2233706
user2233706

Reputation: 7225

Convert byte array to string in Golang template

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.

Upvotes: 2

Views: 4181

Answers (1)

mkopriva
mkopriva

Reputation: 38313

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

`)

Upvotes: 10

Related Questions