根据 url 查询参数创建嵌套结构

我的目标是从数据库中获取一些过滤记录。过滤基于依赖于另一个结构的结构:


type Group struct {

      ID          primitive.ObjectID

      Name        string

}


type Role struct {

    ID          primitive.ObjectID  

    Name        string              

    Description string              

    Groups      []*group.Group     

}

我从 URL 查询参数创建一个角色结构对象:


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?

}

结构的填充name和description字段Role非常简单。整个 url 将是:

myhost/roles?name=rolename&description=roledescription

但是如果我想为Group结构传递数据,url 会是什么样子呢?是否可以在查询参数中将数据作为 json 对象传递?另外,我想提到的那个groups字段Role是一个数组。我理想的虚拟 url 看起来像:myhost/roles?name=rolename&description=roledescription&groups={name:groupname1}&groups={name:groupname2}


小怪兽爱吃肉
浏览 78回答 1
1回答

哈士奇WWW

遍历组,拆分:,创建组并附加到切片:roleWP := Role{&nbsp; &nbsp; Name:&nbsp; &nbsp; &nbsp; &nbsp; r.FormValue("name"),&nbsp; &nbsp; Description: r.FormValue("description"),}for _, g := range r.Form["groups"] {&nbsp; &nbsp; g = strings.TrimPrefix(g, "{")&nbsp; &nbsp; g = strings.TrimSuffix(g, "}")&nbsp; &nbsp; i := strings.Index(g, ":")&nbsp; &nbsp; if i < 0 {&nbsp; &nbsp; &nbsp; &nbsp; // handle error&nbsp; &nbsp; }&nbsp; &nbsp; roleWP.Groups = append(roleWP.Groups, &Group{g[:i], g[i+1:]})}以下是如何使用 JSON 而不是 OP 的理想格式:roleWP := Role{&nbsp; &nbsp; Name:&nbsp; &nbsp; &nbsp; &nbsp; r.FormValue("name"),&nbsp; &nbsp; Description: r.FormValue("description"),}for _, s := range r.Form["groups"] {&nbsp; &nbsp; var g Group&nbsp; &nbsp; err := json.Unmarshal([]byte(s), &v)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; // handle error&nbsp; &nbsp; }&nbsp; &nbsp; roleWP.Groups = append(roleWP.Groups, &g)}
打开App,查看更多内容
随时随地看视频慕课网APP