gpt4 book ai didi

go - 来自 PostForm 的 Gin Gonic 值数组

转载 作者:IT王子 更新时间:2023-10-29 00:41:59 24 4
gpt4 key购买 nike

我正在尝试使用 Go/Gin Gonic 从 HTML 表单中捕获一组 Post 值——在 PHP 中我会使用类似的东西:

<form method="POST" enctype="multipart/form-data" action="mygo">
<input type=hidden name="emails[]" value="email1@email.com">
<input type=hidden name="emails[]" value="email2@email.com">
<input type=hidden name="emails[]" value="email3@email.com">
</form>

然而,这似乎不适用于 Gin Gonic(或 Go)。

我也试过:

<form method="POST" enctype="multipart/form-data" action="mygo">
<input type=hidden name="emails" value="email1@email.com">
<input type=hidden name="emails" value="email2@email.com">
<input type=hidden name="emails" value="email3@email.com">
</form>

与其他地方一样,建议这样做会导致 c.PostForm("emails") 返回一个 slice 。但是在实践中,这似乎反而将最后一个值作为字符串返回:(

有趣的是,即使首先调用了 c.Request.ParseForm()c.Request.PostForm 也会返回一个空映射。我做错了什么?

去表格:

func main() {
// ...
router.POST("mygo",parseFunc)
}

func mygo(c *gin.Context) {
c.Request.ParseForm()
log.Printf("%v",c.Request.PostForm["emails"]) // ""
log.Printf("%v",c.PostForm("emails") // "email3@email.com"
}

最佳答案

为了让它工作,你有两种方法

<form method="POST" enctype="multipart/form-data" action="mygo">
<input type=hidden name="emails" value="email1@email.com">
<input type=hidden name="emails" value="email2@email.com">
<input type=hidden name="emails" value="email3@email.com">
</form>

r.POST("/", func(c *gin.Context) {
c.Request.ParseMultipartForm(1000)
for key, value := range c.Request.PostForm {
fmt.Println(key,value)
}
})

要么

    <form method="POST" action="mygo">
<input type=hidden name="emails" value="email1@email.com">
<input type=hidden name="emails" value="email2@email.com">
<input type=hidden name="emails" value="email3@email.com">
</form>

r.POST("/", func(c *gin.Context) {
c.Request.ParseForm()
for key, value := range c.Request.PostForm {
fmt.Println(key,value)
}
})

两者给出相同的结果

emails [email1@email.com email2@email.com email3@email.com]

关于go - 来自 PostForm 的 Gin Gonic 值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39984575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com