Search code examples
gogo-templates

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.


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