You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编译Go代码时遇rego.ReadFile未定义错误求助

编译Go代码时rego.ReadFile未定义错误的解决方法

错误信息

编译时触发如下错误:

-bash-4.2$ go build main.go 
# command-line-arguments
./main.go:20:26: undefined: rego.ReadFile

相关代码

discount_policy.rego

package discounts

rule "Bronze Discount"
    salience 10
    when
        Customer loyaltyLevel == "Bronze"
    then
        Discount.percent = 5;
        Discount.message = "You have earned a 5% discount!";
end

rule "Default Discount"
    salience 0
    then
        Discount.percent = 0;
        Discount.message = "Sorry, no discount available.";
end

main.go(原错误代码)

package main

import (
        "context"
        "fmt"

        "github.com/open-policy-agent/opa/rego"
)

type Customer struct {
        LoyaltyLevel string `json:"loyaltyLevel"`
}

type Discount struct {
        Percent int    `json:"percent"`
        Message string `json:"message"`
}

func LoadPolicy() (*rego.Rego, error) {
        regoPolicy, err := rego.ReadFile("discount_policy.rego")
        if err != nil {
                return nil, fmt.Errorf("failed to load policy file: %w", err)
        }

        return rego.New(
                rego.Query("data.discounts.Discount"),
                rego.Compiler(regoPolicy),
        ), nil
}        

func main() {
        // Load the GRules policy
        r, err := LoadPolicy()
        if err != nil {
                fmt.Println("Policy loading error:", err)
                return
        }
}

解决方法

rego.ReadFile并非OPA rego包的标准公开API,该函数不存在导致编译失败。正确的策略加载方式有两种:

方法一:直接通过rego.File指定文件路径

由OPA SDK内部处理文件读取与编译逻辑,代码更简洁:

func LoadPolicy() (*rego.Rego, error) {
        return rego.New(
                rego.Query("data.discounts.Discount"),
                rego.File("discount_policy.rego"), // 直接传入策略文件路径
        ), nil
}

方法二:手动读取文件后通过rego.Module传入

若需要对文件内容做预处理,可使用标准库os.ReadFile读取内容,再传递给SDK:

import "os"

func LoadPolicy() (*rego.Rego, error) {
        policyContent, err := os.ReadFile("discount_policy.rego")
        if err != nil {
                return nil, fmt.Errorf("failed to load policy file: %w", err)
        }

        return rego.New(
                rego.Query("data.discounts.Discount"),
                rego.Module("discount_policy.rego", string(policyContent)),
        ), nil
}

修改代码后重新编译即可解决该错误。

内容的提问来源于stack exchange,提问作者van neilsen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 09:15:01