SandaleRaclette
SandaleRaclette

Reputation: 119

Map correctly YAML config file in golang

I write an API in go which can create organisation which have default policies rules.

I want to use an external config YAML file to include some policies in my API (I actually put the policies inside my code in the function which creates my entity organisation) :

policy.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"}]

I extract it using go-yaml lib and the expected output should be :

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

But when I extract it in a struct like :

// 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
}

I get this :

[{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]]}]

Maybe I don't get well how to use or properly write YAML, so guys could you help me understanding how to map it to obtain the output expected.

Upvotes: 1

Views: 2073

Answers (1)

SandaleRaclette
SandaleRaclette

Reputation: 119

Finally find it, I have to change my Yaml a little to have a proper array, the case seems to be very important too :

- 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"}

and my struct is a bit differents it contains a struct than include my two strings :

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"`
}

Upvotes: 3

Related Questions