go - 如何解析表单后的数组

标签 go

我目前有一个类似的表单帖子

{
 "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/

相关文章:

go - 新函数和未初始化变量的区别

go - 不能在 slice 文字中使用primitive.D字面量(类型primitive.D)作为类型primitive.E

go - 作证模拟单一方法

json - 使用不可打印的 ASCII 字符解码 JSON

戈朗 : Walk Directory Tree and Process Files -- err = 'no such file or directory

go - 显示巨大的十六进制字符串的基数 10 表示?

go - golang channel 内存使用是动态的吗?

go - 方法接收者和参数有什么区别?

go - 在golang中安装外部包

go - 获取基于原始类型的类型的 reflect.Kind