在Go语言中解析数组形式的表单数据

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

Parsing Array Post Form Data in Go

问题

所以我有这个表单:

<form method="POST" action="/parse">
	<div>	
		<input name="photo[0]" value="嘿,我是第一张照片!" />
	</div>
	<div>
		<input name="photo[1]" value="这是第二张照片!" />
	</div>
	<div>
		<input name="photo[2]" value="哎呀,我是第三张照片,但我是第二张照片..." />
	</div>
	<div>
		<button type="submit">提交</button>
	</div>
</form>

在Go中,似乎可以使用net/http库通过表单中的字符串键逐个查询表单数据:

r.PostFormValue("photo[0]")

在Go中有没有一种简单的方法可以直接将这个表单解析为切片?

也就是说,能够像这样访问photo的元素:

photos := r.PostFormValue("photo");
log.Println(photos[1]);

或者除了字符串操作之外,还有没有其他方法可以正确访问表单提交数据中的“类似数组”的数据结构?

英文:

So I have this form:

<form method="POST" action="/parse">
	<div>	
		<input name="photo[0]" value="Hey I'm photo zero!" />
	</div>
	<div>
		<input name="photo[1]" value="Photo one here!" />
	</div>
	<div>
		<input name="photo[2]" value="Awh I'm photo 2 but I'm the third photo..." />
	</div>
	<div>
		<button type="submit">submit</button>
	</div>
</form>

In Go, it appears, the net/http library will allow you to query the form data one at a time by string key in the form:

r.PostFormValue("photo[0]")

Is there an easy way to parse this form directly as a slice in Go?

That is, being able to access the elements of photo like this:

photos := r.PostFormValue("photo");
log.Println(photos[1]);

Or any other suggestion on properly accessing 'array like' data structures in form post data in Golang aside from string munging...

答案1

得分: 4

不要在名称中添加数组索引,对所有输入使用相同的名称。http库将解析具有相同名称的字段为一个切片。

英文:

Don’t add array index in name, use same name for all inputs.
The http library will parse field with the same name to a slice.

<form method="POST" action="/parse">
    <div>   
        <input name="photo" value="Hey I'm photo zero!" />
    </div>
    <div>
        <input name="photo" value="Photo one here!" />
    </div>
    <div>
        <input name="photo" value="Awh I'm photo 2 but I'm the third photo..." />
    </div>
    <div>
        <button type="submit">submit</button>
    </div>
</form>

huangapple
  • 本文由 发表于 2014年7月20日 18:18:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/24849493.html
匿名

发表评论

匿名网友

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

确定