Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

`)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading