Skip to content

Instantly share code, notes, and snippets.

@srenatus
Created October 31, 2022 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srenatus/731347035242865b395f434e8bcc5514 to your computer and use it in GitHub Desktop.
Save srenatus/731347035242865b395f434e8bcc5514 to your computer and use it in GitHub Desktop.
opa wasm example
  1. put example_main.go in example/main.go in an OPA checkout
  2. compile via Go: GOOS=js GOARCH=wasm go build -o example.wasm ./example/
  3. Use with wasm_exec.js, and some index.html
  4. call opa.parse("package foo") in the browser's dev tools console
package main
import (
"syscall/js"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/format"
)
func main() {
done := make(chan struct{})
js.Global().Set("opa", make(map[string]interface{}))
module := js.Global().Get("opa")
module.Set("parse",
js.FuncOf(func(this js.Value, args []js.Value) interface{} {
if args == nil {
panic("initialize: not enough args")
}
mod, err := ast.ParseModule("a.rego", args[0].String())
m := map[string]interface{}{}
if err != nil {
m["error"] = err.Error()
} else {
m["result"] = formatMod(mod)
}
return m
}),
)
<-done
}
func formatMod(m *ast.Module) string {
out, err := format.Ast(m)
if err != nil {
panic(err)
}
return string(out)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment