-
Notifications
You must be signed in to change notification settings - Fork 9
/
marshal.go
37 lines (32 loc) · 967 Bytes
/
marshal.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
package main
import (
"encoding/json"
"fmt"
"syscall/js"
)
func marshalStruct(obj any) (js.Value, error) {
jsonData, err := json.Marshal(obj)
if err != nil {
return js.Null(), err
}
jsObject := js.Global().Get("JSON").Call("parse", string(jsonData))
return jsObject, nil
}
func unmarshalStruct(jsValue js.Value, target any) error {
jsonData := js.Global().Get("JSON").Call("stringify", jsValue).String()
return json.Unmarshal([]byte(jsonData), target)
}
func unmarshalUint8Array(jsArray js.Value) ([]uint8, error) {
if jsArray.Type() != js.TypeObject || jsArray.Get("constructor").Get("name").String() != "Uint8Array" {
return nil, fmt.Errorf("expected Uint8Array")
}
length := jsArray.Length()
goBytes := make([]byte, length)
js.CopyBytesToGo(goBytes, jsArray)
return goBytes, nil
}
func marshalUint8Array(bytes []byte) js.Value {
jsArray := js.Global().Get("Uint8Array").New(len(bytes))
js.CopyBytesToJS(jsArray, bytes)
return jsArray
}