-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathv8tpl.go
67 lines (55 loc) · 1.81 KB
/
v8tpl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
Package v8tpl enables to evaluate JavaScript templates in Go.
JavaScript template must implement function `template(data)` that will be called. Simple template:
var template = function(data) {
return "Hello " + data.name;
}
*/
package v8tpl
/*
#cgo CFLAGS: -I${SRCDIR}/v8/include -I${SRCDIR}/v8
#cgo CXXFLAGS: -pthread -std=c++0x -I${SRCDIR}/v8/include -I${SRCDIR}/v8
#cgo LDFLAGS: -Wl,--start-group ${SRCDIR}/v8/out/native/obj.target/src/libv8_base.a ${SRCDIR}/v8/out/native/obj.target/src/libv8_nosnapshot.a ${SRCDIR}/v8/out/native/obj.target/src/libv8_libbase.a ${SRCDIR}/v8/out/native/obj.target/src/libv8_libplatform.a ${SRCDIR}/v8/out/native/obj.target/src/libv8_libsampler.a ${SRCDIR}/v8/out/native/obj.target/src/libv8_builtins_setup.a ${SRCDIR}/v8/out/native/obj.target/src/libv8_builtins_generators.a -Wl,--end-group -lrt -ldl
#include "v8binding.h"
#include "stdlib.h"
*/
import "C"
import (
"encoding/json"
"errors"
"runtime"
"unsafe"
)
func init() {
C.init_v8()
}
// Template is a class for evaluating JS templates.
type Template struct {
cTemplate *C.tpl
}
// NewTemplate is a constructor.
func NewTemplate(source string) (*Template, error) {
cTpl := C.new_template(C.CString(source))
lastError := C.get_template_err(cTpl)
if lastError != nil {
return nil, errors.New(C.GoString(lastError))
}
template := &Template{
cTemplate: cTpl,
}
runtime.SetFinalizer(template, func(t *Template) {
C.destroy_template(t.cTemplate)
})
return template, nil
}
// Eval evaluate JS template and return string or error if something went wrong.
func (t *Template) Eval(v interface{}) (string, error) {
data, err := json.Marshal(v)
if err != nil {
return "", err
}
cStr := C.eval_template(t.cTemplate, C.CString("template("+string(data)+");"))
res := C.GoString(cStr)
C.free(unsafe.Pointer(cStr))
return res, nil
}