Repository navigation
Expand file tree
/
Copy pathyamlscript.go
More file actions
73 lines (62 loc) · 1.67 KB
/
Copy pathyamlscript.go
File metadata and controls
73 lines (62 loc) · 1.67 KB
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
68
69
70
71
72
73
package yamlscript
// #cgo LDFLAGS: -lys
// #ifdef _WIN32
// #include <libys.h>
// #else
// #include <libys.0.3.7.h>
// #endif
// #include <stdlib.h>
import "C"
import (
"encoding/json"
"errors"
"log"
"runtime"
"unsafe"
)
// Create a new GraalVM isolate for life of the package
var isolate *C.graal_isolate_t
// YAMLScript package constructor
func init() {
// Create the isolate without creating an initial thread
// We'll attach threads as needed per-call
rc := C.graal_create_isolate(nil, &isolate, nil)
if rc != 0 {
log.Fatal("Failed to create isolate")
}
}
// Compile and eval a YAMLScript string and return the result
func Load(input string) (data any, err error) {
// Lock the OS thread for GraalVM native image calls
runtime.LockOSThread()
defer runtime.UnlockOSThread()
// Attach a thread for this call
var thread *C.graal_isolatethread_t
rc := C.graal_attach_thread(isolate, &thread)
if rc != 0 {
return nil, errors.New("Failed to attach thread")
}
defer C.graal_detach_thread(thread)
cs := C.CString(input)
// Call 'load_ys_to_json' function in libys shared library:
// Use the newly attached thread
data_json := C.GoString(C.load_ys_to_json(thread, cs))
C.free(unsafe.Pointer(cs))
// Decode the JSON response:
var resp map[string]any
err = json.Unmarshal([]byte(data_json), &resp)
if err != nil {
return
}
// Check for libys error in JSON response:
if error_json, ok := resp["error"]; ok {
err = errors.New(error_json.(map[string]any)["cause"].(string))
return
}
// Get the response object from evaluating the YAMLScript string:
var ok bool
if data, ok = resp["data"]; !ok {
err = errors.New("unexpected response from 'libys'")
}
return
}