Skip to content

Instantly share code, notes, and snippets.

@developer-guy
Created June 16, 2020 07:02
Show Gist options
  • Save developer-guy/02f84ab68b27fa310adcf0a90ac0d11c to your computer and use it in GitHub Desktop.
Save developer-guy/02f84ab68b27fa310adcf0a90ac0d11c to your computer and use it in GitHub Desktop.
opaAsGoLib
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"github.com/open-policy-agent/opa/rego"
)
func main() {
ctx := context.Background()
// Construct a Rego object that can be prepared or evaluated.
r := rego.New(
rego.Query(os.Args[2]),
rego.Load([]string{os.Args[1]}, nil))
// Create a prepared query that can be evaluated.
query, err := r.PrepareForEval(ctx)
if err != nil {
log.Fatal(err)
}
// Load the input document from stdin.
var input interface{}
dec := json.NewDecoder(os.Stdin)
dec.UseNumber()
if err := dec.Decode(&input); err != nil {
log.Fatal(err)
}
// Execute the prepared query.
rs, err := query.Eval(ctx, rego.EvalInput(input))
if err != nil {
log.Fatal(err)
}
// Do something with the result.
fmt.Println(rs)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment