gpt4 book ai didi

go - 在 golang 中正确映射 YAML 配置文件

转载 作者:数据小太阳 更新时间:2023-10-29 03:11:15 24 4
gpt4 key购买 nike

我用 go 编写了一个 API,它可以创建具有默认策略规则的组织。

我想使用外部配置 YAML 文件在我的 API 中包含一些策略(我实际上将这些策略放在我的代码中的函数中,该函数创建了我的实体组织):

策略.yml

- role: "admin"
organisationid: organisation.ID
policies:
[{Object: "/*", Action: "*"}]

- role: "user"
organisationid: organisation.ID
policies:
[{Object: "/me", Action: "GET"},
{Object: "/organisations", Action: "GET"},
{Object: "/acl/roles", Action: "GET"}]

我使用 go-yaml 提取它lib 和预期的输出应该是:

[{admin organisation.ID [{/* *}]} {user organisation.ID [{/me GET} {/organisations GET} {/acl/roles GET}]}]

但是当我将它提取到类似这样的结构中时:

// OrganisationRole ...
type OrganisationRoleNoPolicy struct {
Role string `json:"role"`
OrganisationID string `json:"organisation"`
Policies []map[string]string `json:"policies"`
}

func extractYaml() (config []OrganisationRoleNoPolicy) {

filename := "policy.yml"
source, err := ioutil.ReadFile(filename)
if err != nil {
panic(err)
}
err = yaml.Unmarshal(source, &config)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- config:\n%v\n\n", config)
return
}

我明白了:

[{admin organisation.ID [map[Object:/* Action:*]]} {user organisation.ID [map[Object:/me Action:GET] map[Object:/organisations Action:GET] map[Object:/acl/roles Action:GET]]}]

也许我不太了解如何使用或正确编写 YAML,所以你们能帮我理解如何映射它以获得预期的输出。

最佳答案

终于找到了,我必须稍微更改一下 Yaml 以获得合适的数组,大小写似乎也很重要:

- role: "admin"
organisationid: organisation.ID
policies:
- {object: "/*", action: "*"}

- role: "user"
organisationid: organisation.ID
policies:
- {object: "/me", action: "GET"}
- {object: "/organisations", action: "GET"}
- {object: "/acl/roles", action: "GET"}

我的结构有点不同,它包含一个结构而不是包含我的两个字符串:

type policy struct {
Object string `json:"obj" binding:"required"`
Action string `json:"act" binding:"required"`
}

// OrganisationRole ...
type OrganisationRole struct {
Role string `json:"role"`
OrganisationID string `json:"organisation"`
Policies []policy `json:"policies"`
}

关于go - 在 golang 中正确映射 YAML 配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51205942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com