package main
import "C"
import (
"bytes"
"encoding/json"
"fmt"
htmltemplate "html/template" texttemplate "text/template" "unsafe" )
type RenderResult struct {
Output string
Error string
}
func renderGoTemplate(templateContent string, jsonData string, escapeHtml bool, useMissingKeyZero bool) RenderResult {
var data map[string]interface{}
err := json.Unmarshal([]byte(jsonData), &data)
if err != nil {
return RenderResult{
Error: fmt.Sprintf("Failed to unmarshal JSON data: %v", err),
}
}
var buf bytes.Buffer
tmplOptions := "missingkey="
if useMissingKeyZero {
tmplOptions += "zero"
} else {
tmplOptions += "default"
}
if escapeHtml {
tmpl := htmltemplate.New("goTemplate").Option(tmplOptions)
tmpl, err = tmpl.Parse(templateContent)
if err != nil {
return RenderResult{
Error: fmt.Sprintf("Failed to parse HTML template: %v", err),
}
}
err = tmpl.Execute(&buf, data)
if err != nil {
return RenderResult{
Error: fmt.Sprintf("Failed to execute HTML template: %v", err),
}
}
} else {
tmpl := texttemplate.New("goTemplate").Option(tmplOptions)
tmpl, err = tmpl.Parse(templateContent)
if err != nil {
return RenderResult{
Error: fmt.Sprintf("Failed to parse Text template: %v", err),
}
}
err = tmpl.Execute(&buf, data)
if err != nil {
return RenderResult{
Error: fmt.Sprintf("Failed to execute Text template: %v", err),
}
}
}
return RenderResult{
Output: buf.String(),
Error: "",
}
}
func RenderTemplate(cTemplateContent *C.char, cJsonData *C.char, cEscapeHtml C._Bool, cUseMissingKeyZero C._Bool) C.RenderResult {
templateContent := C.GoString(cTemplateContent)
jsonData := C.GoString(cJsonData)
escapeHtml := bool(cEscapeHtml)
useMissingKeyZero := bool(cUseMissingKeyZero)
result := renderGoTemplate(templateContent, jsonData, escapeHtml, useMissingKeyZero)
cOutput := C.CString(result.Output)
cError := C.CString(result.Error)
return C.RenderResult{
output: cOutput,
error: cError,
}
}
func FreeResultString(cStr *C.char) {
C.free(unsafe.Pointer(cStr))
}
func main() {
}