Create nested struct based on url query parameters

Issue

My goal is to get some filtered records from database. Filtration is based on a struct which depends on another struct:

type Group struct {
      ID          primitive.ObjectID
      Name        string
}

type Role struct {
    ID          primitive.ObjectID  
    Name        string              
    Description string              
    Groups      []*group.Group     
}

I create an object of Role struct from URL query parameters:

var roleWP Role
if r.URL.Query().Has("name") {
    name := r.URL.Query().Get("name")
    roleWP.Name = name
}
if r.URL.Query().Has("description") {
    description := r.URL.Query().Get("description")
    roleWP.Description = description
}
if r.URL.Query().Has("groups") {
   //How would look groups parameter?
}

Filling name and description fields of Role struct is pretty simple. The whole url would be:
myhost/roles?name=rolename&description=roledescription
But how would look url if I want to pass data for Group struct? Is it possible to pass data as a json object in query parameter? Also, I want to mention that groups field in Role is an array. My ideal dummy url would look like: myhost/roles?name=rolename&description=roledescription&groups={name:groupname1}&groups={name:groupname2}

Solution

Loop through the groups, split on :, create group and append to slice:

roleWP := Role{
    Name:        r.FormValue("name"),
    Description: r.FormValue("description"),
}
for _, g := range r.Form["groups"] {
    g = strings.TrimPrefix(g, "{")
    g = strings.TrimSuffix(g, "}")
    i := strings.Index(g, ":")
    if i < 0 {
        // handle error
    }
    roleWP.Groups = append(roleWP.Groups, &Group{g[:i], g[i+1:]})
}

Here’s how to use JSON instead of OP’s ideal format:

roleWP := Role{
    Name:        r.FormValue("name"),
    Description: r.FormValue("description"),
}
for _, s := range r.Form["groups"] {
    var g Group
    err := json.Unmarshal([]byte(s), &v)
    if err != nil {
        // handle error
    }
    roleWP.Groups = append(roleWP.Groups, &g)
}

Answered By – mandy

Answer Checked By – Dawn Plyler (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.