我目前有一个类似的表单帖子
{
"stuff":"cool text",
"otherthing":"neat thing",
"captions":[
{"first":"the list",
"second":"how are you"},
{"first":"wow",
etc....
]
}
现在我不知道会有多少字幕。它可能是数组中的一个,可能是二十个。
我也建立了两个结构
type ThingContext struct {
Stuff string `json:"stuff"`
OtherThing string `json:"otherthing"`
Captions []ArrayText `json:"captions"`
}
type ArrayText struct {
First string `json:"first"`
Second string `json:"second"`
}
在我的golang函数中,我有这样的东西
func (c *ThingContext) SetThingContext(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
if err := req.ParseForm(); err != nil {
}
c.Stuff = req.FormValue("stuff")
c.OtherThing = req.FormValue("otherthing")
}
在我尝试解析数组之前,此方法工作正常。
当我按照
c.Captions = req.ParseForm("captions")
的方式进行操作时我得到了错误
.cannot use req.Request.ParseForm("captions") (type error) as type []ArrayText in assignment
最佳答案
您的工作做对了,除了任务。当您运行req.Request.ParseForm()而不是返回值或传递对缓冲区的引用时,它将填充req.Request.Form和req.Request.PostForm结构。
The related GoDoc explaining said function
所以,而不是
c.Captions = req.Request.ParseForm()
看起来更像
err := req.Request.ParseForm()
//check for errors as usual here
c.Captions = req.Request.Form
//or
c.Captions = req.Request.PostForm
从这个方向接近它应该使您走上正确的道路。
干杯!
泰勒
关于go - 如何解析表单后的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58142151/