Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 933
user2233706 Avatar asked Dec 10 '25 04:12

user2233706


1 Answers

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

`)
like image 87
mkopriva Avatar answered Dec 11 '25 23:12

mkopriva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!