- put
example_main.go
inexample/main.go
in an OPA checkout - compile via Go:
GOOS=js GOARCH=wasm go build -o example.wasm ./example/
- Use with wasm_exec.js, and some index.html
- call
opa.parse("package foo")
in the browser's dev tools console
Created
October 31, 2022 19:14
-
-
Save srenatus/731347035242865b395f434e8bcc5514 to your computer and use it in GitHub Desktop.
opa wasm example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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