Last active
April 27, 2018 18:43
-
-
Save tehmoon/2f0ca396a6662e837d1c11a6adbc3b91 to your computer and use it in GitHub Desktop.
Using Go templating engine with JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"os" | |
"text/template" | |
) | |
var data = map[string]interface{}{ | |
"blih": true, | |
"blah": map[string]interface{}{ | |
"bluh": "false", | |
}, | |
"bloh": []int{1,2,3,4,5}, | |
} | |
var jsonFunc = template.FuncMap{ | |
"json": func(d interface{}) string { | |
payload, err := json.Marshal(d) | |
if err != nil { | |
return "" | |
} | |
return string(payload[:]) | |
}, | |
"json_indent": func(d interface{}) (string) { | |
payload, err := json.MarshalIndent(d, "", " ") | |
if err != nil { | |
return "" | |
} | |
return string(payload[:]) | |
}, | |
"newline": func() (string) { | |
return "\n" | |
}, | |
} | |
func main() { | |
tmpl, err := template.New("test").Funcs(jsonFunc).Parse("{{json . | js}}") | |
if err != nil { | |
panic(err) | |
} | |
err = tmpl.Execute(os.Stdout, data) | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment