英文:
OPA (Rego) as Go lib: How to apply external data?
问题
我按照https://www.openpolicyagent.org/docs/latest/#5-try-opa-as-a-go-library的示例进行了操作。重要的代码片段:
r := rego.New(
rego.Query("x = data.example.allow"),
rego.Load([]string{"./example.rego"}, nil)
...
rs, err := query.Eval(ctx, rego.EvalInput(input))
...
我该如何添加外部数据(data.json),以便在rego策略中使用,例如data.wantedName来访问它?
我尝试阅读go文档和示例,但没有找到有用的信息。
谢谢!
英文:
I followed the example of https://www.openpolicyagent.org/docs/latest/#5-try-opa-as-a-go-library. Important code snippets:
r := rego.New(
rego.Query("x = data.example.allow"),
rego.Load([]string{"./example.rego"}, nil)
...
rs, err := query.Eval(ctx, rego.EvalInput(input))
...
How can I add external data (data.json) such that I can use, e.g., data.wantedName in the rego policy to access it?
I tried to read through the go doc and the examples but I couldn't find any helpful information.
Thanks!
答案1
得分: 6
你看过rego.Store()的文档和这个示例吗?
对于简单的情况,可以按照以下方式进行操作:
	data := `{
        "example": {
            "users": [
                {
                    "name": "alice",
                    "likes": ["dogs", "clouds"]
                },
                {
                    "name": "bob",
                    "likes": ["pizza", "cats"]
                }
            ]
        }
    }`
	var json map[string]interface{}
	err := util.UnmarshalJSON([]byte(data), &json)
	if err != nil {
		// 处理错误。
	}
	store := inmem.NewFromObject(json)
	// 创建返回值的新查询
	rego := rego.New(
		rego.Query("data.example.users[0].likes"),
		rego.Store(store))
如果需要更复杂的用法,你可以自己实现存储方式,但这将会更加复杂。如果可以通过将inmem.NewFromObject()存储传递给rego.New()来解决问题,建议首先尝试这种方法。
英文:
Have you seen the docs on rego.Store() and this example?
Something along these lines should do the trick for simple cases:
	data := `{
        "example": {
            "users": [
                {
                    "name": "alice",
                    "likes": ["dogs", "clouds"]
                },
                {
                    "name": "bob",
                    "likes": ["pizza", "cats"]
                }
            ]
        }
    }`
	var json map[string]interface{}
	err := util.UnmarshalJSON([]byte(data), &json)
	if err != nil {
		// Handle error.
	}
	store := inmem.NewFromObject(json)
	// Create new query that returns the value
	rego := rego.New(
		rego.Query("data.example.users[0].likes"),
		rego.Store(store))
You could implement your own storage for more intricate uses, but that's going to be a lot more involved. If you get by with feeding inmem.NewFromObject() stores into rego.New(), you should try that first.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论