根据URL查询参数创建嵌套结构体。

huangapple go评论82阅读模式
英文:

Create nested struct based on url query parameters

问题

我的目标是从数据库中获取一些经过筛选的记录。筛选是基于一个依赖于另一个结构体的结构体进行的:

type Group struct {
    ID   primitive.ObjectID
    Name string
}

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

我从URL查询参数创建了一个Role结构体的对象:

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") {
    // groups参数会是什么样子?
}

填充Role结构体的namedescription字段非常简单。整个URL应该是:myhost/roles?name=rolename&description=roledescription

但是,如果我想传递Group结构体的数据,URL会是什么样子呢?是否可以将数据作为JSON对象传递给查询参数?另外,我想提一下,Role中的groups字段是一个数组。我理想中的虚拟URL应该是:myhost/roles?name=rolename&description=roledescription&groups={name:groupname1}&groups={name:groupname2}

英文:

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: <br> myhost/roles?name=rolename&description=roledescription<br>
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}

答案1

得分: 1

循环遍历组,根据":"进行分割,创建组并添加到切片中:

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 {
        // 处理错误
    }
    roleWP.Groups = append(roleWP.Groups, &Group{g[:i], g[i+1:]})
}

以下是如何使用JSON替代OP的理想格式:

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

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

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

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

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

huangapple
  • 本文由 发表于 2022年3月29日 22:15:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/71663732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定