1

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}

Kas
  • 89
  • 8
  • Have you considered using a POST request rather than a GET request? You could then specify the query in the request body. – jub0bs Mar 29 '22 at 14:45

1 Answers1

1

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)
}
mandy
  • 26
  • 2
  • Thanks for the answer. Is it a good practice to pass data as a json object? – Kas Mar 29 '22 at 14:28
  • I'm following the REST principle and my request method is GET. I've read about request body [here](https://stackoverflow.com/questions/978061/http-get-with-request-body) – Kas Mar 29 '22 at 14:35