Skip to content

Instantly share code, notes, and snippets.

@rudolph9
Last active February 4, 2023 00:32
Show Gist options
  • Save rudolph9/dd5e3dbcbf762abdb3f662e39dacfa7f to your computer and use it in GitHub Desktop.
Save rudolph9/dd5e3dbcbf762abdb3f662e39dacfa7f to your computer and use it in GitHub Desktop.
Cue Web Assembly

Cue Web Assembly

Followed tutorial here: https://github.com/golang/go/wiki/WebAssembly

Setup

  1. install compatible version of golang. Test with go1.12.8
  2. get cue: go get -u cuelang.org/go/cue NOTE: this installs the packages files, not the cmd
  3. get the wasm exec_file cp "$(go env GOROOT)/misc/wasm/wasm_exec.js

Build

  1. Build the wasm: GOARCH=wasm GOOS=js go build -o lib.wasm main.go

Serve files

  1. install goexec if needed (or serve the files some other way): go get -u github.com/shurcooL/goexec

  2. Serve files: goexec 'http.ListenAndServe(":8080", http.FileServer(http.Dir(".")))'

<!DOCTYPE html>
<!--
Copyright 2018 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<html>
<head>
<meta charset="utf-8" />
<title>Go wasm</title>
</head>
<body>
<script src="wasm_exec.js"></script>
<script>
if (!WebAssembly.instantiateStreaming) {
// polyfill
WebAssembly.instantiateStreaming = async (resp, importObject) => {
const source = await (await resp).arrayBuffer();
return await WebAssembly.instantiate(source, importObject);
};
}
const go = new Go();
let mod, inst;
WebAssembly.instantiateStreaming(fetch("lib.wasm"), go.importObject).then(
result => {
mod = result.module;
inst = result.instance;
document.getElementById("runButton").disabled = false;
}
);
async function run() {
await go.run(inst);
inst = await WebAssembly.instantiate(mod, go.importObject); // reset instance
}
</script>
<button onClick="run();" id="runButton" disabled>Run</button>
</body>
</html>
package main
import (
"fmt"
"math/big"
"cuelang.org/go/cue"
)
func main() {
const config = `
TimeSeries: {
"2019-09-01T07:00:00Z": 36
}
TimeSeries: {
"2019-09-01T07:10:59Z": 200
}
`
var r cue.Runtime
instance, err := r.Compile("test", config)
if err != nil {
fmt.Println(err)
}
var bigInt big.Int
instance.Lookup("TimeSeries").Lookup("2019-09-01T07:10:59Z").Int(&bigInt)
fmt.Println(bigInt.String())
}
// get this file by running `cp "$(go env GOROOT)/misc/wasm/wasm_exec.js"`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment