遍历多个表单值,并将其中一些放入结构切片中。

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

traverse through multiple form values and put some of them inside struct slices

问题

我现在是你的中文翻译助手,以下是翻译好的内容:

我处于这样一种情况:我想将未知数量的输入值放入我的Go结构体中,但只有其中一些将被放入切片/数组中。这是HTML内容的一部分示例:

...

{{ range .users }}

遍历多个表单值,并将其中一些放入结构切片中。
{{ .Username }} {{ .Age }} {{ .Email }}


{{end}}

...
{{ .csrfField }}

// 提交按钮

其中{{ .csrfField }}将生成一个隐藏的输入。这部分工作正常。

现在的问题是如何将这些数据放入结构体中?

假设我有以下结构体:

type UserFormData struct {
UserID int
Username string
AvatarThumbnailURL string
Age int
Email string
}

但在我的POST函数中,我不知道有多少用户将通过表单提交。所以我猜我必须这样做:

userFormData := make([]UserFormData, len(r.PostForm)/6)

(除以6,因为有AvatarThumbnailURL、Username、Age、Email、UserID和csrfField)

然后可以像这样遍历r.PostForm:

i := 0
j := 0
for key, values := range r.PostForm {
switch key {
case "userid":
userid, _ := strconv.Atoi(values[0])
userFormData[j].UserID = userid
case "thumbnail":
userFormData[j].Thumbnail = values[0]
// 其他字段
i++
if i%6 == 0 {
j++
}
}

虽然这样可以工作,但极易出错,容易超出索引范围,而且每当我进行更改时,都必须计算将与表单一起发送的输入值的数量,并更新当前的'6'值。我毫不怀疑肯定有一种更好的方法来做到这一点,如果有人能指点我正确的方向,我将非常感激 遍历多个表单值,并将其中一些放入结构切片中。

英文:

I'm in a situation where I want to get an unknown number of input values into my Go structs, but only some of them will be placed inside a slice/array. Here's a snippet of the HTML content:

<form action="/" method="post">
...
<tbody>
    {{ range .users }}
    <tr>
        <td class="text-center">
            <img class="avatar" src="{{ .AvatarThumbnailURL }}">
            <input type="hidden" name="thumbnail" value="{{ .AvatarThumbnailURL }}">
        </td>
        <td>
            {{ .Username }}<input type="hidden" name="username" value="{{ .Username }}">
        </td>
        <td>
            {{ .Age }}<input type="hidden" name="age" value="{{ .Age }}">
        </td>
        <td>
            {{ .Email }}<input type="hidden" name="email" value="{{ .Email }}">
        </td>
    </tr>
    <input type="hidden" name="userid" value="{{ .UserID }}">
    {{end}}
</tbody>
...
{{ .csrfField }}

// submit button

</form>

Where {{ .csrfField }} will generate a hidden input. This part is working fine.

Now the problem is how do I get this data inside a struct?

Let's say I have the following struct:

type UserFormData struct {
   UserID int
   Username string
   AvatarThumbnailURL string
   Age int
   Email string
}

But in my POST function I don't know how many users will be submitted through the form. So I guess I have to do something like this:

userFormData := make([]UserFormData, len(r.PostForm)/6) 

(divided by 6 because there are AvatarThumbnailURL, Username, Age, Email, UserID and csrfField)

Then can go through the r.PostForm like this:

i := 0
j := 0
for key, values := range r.PostForm {
	switch key {
	case "userid":
		userid, _ := strconv.Atoi(values[0])
		userFormData[j].UserID = userid
	case "thumbnail":
		userFormData[j].Thumbnail = values[0]
	// the other fields
	i++
	if i%6 == 0 {
		j++
	}
}

While this work, it's extremely error prone to indexoutofrange and whenever I make a change then I have to count number of input values that will be sent with the form and update the (currently) '6' values. I have no doubt that there must be a much, much, much better way to do this, and I would greatly appreciate if someone could point me in the right direction 遍历多个表单值,并将其中一些放入结构切片中。

答案1

得分: 2

你可以利用r.PostForm实际上是一个映射,其中键是字段名,值是字符串数组的事实,所以你可以按照以下方式进行操作(我没有测试过,但是这个概念应该是可行的)。

我们遍历"userid"字段的所有值,以了解有多少个用户。此外,你可以使用append将用户动态添加到切片中。

userFormData := []UserFormData{}
for i, userId := range r.PostForm["userid"] {
    user := UserFormData{
        UserID:    userId,
        Thumbnail: r.PostForm["thumbnail"][i],
    }
    userFormData = append(userFormData, user)
}
英文:

You can take use the fact that r.PostForm is actually a map where keys are the field names and values are an array of strings, so you can do something along these lines (I didn't test it, but the concept should work).

We iterate over all values for the "userid" field to know how many users there are. Also, you can use append to add users dynamically to the slice.

userFormData := []UserFormData{}
for i, userId := range r.PostForm["userid"] {
     user := UserFormData{
        UserID: userId,
        Thumbnail: r.PostForm["thumbnail"][i],
     }
     userFormData = append(userFormData, user)
}

huangapple
  • 本文由 发表于 2017年7月28日 04:02:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/45360045.html
匿名

发表评论

匿名网友

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

确定