如何在Go Fiber中获取HTML表单同名的多个值?
在Go Fiber中获取同名表单参数的所有值
要获取表单中同名参数的所有值,直接使用Fiber上下文提供的c.FormValues()方法即可,它会返回对应参数名的所有值组成的[]string切片。
示例代码
假设你的路由处理函数如下:
app.Post("/providers", func(c *fiber.Ctx) error { // 获取所有名为state的参数值 states := c.FormValues("state") // 例如选中Provider1和Provider3时,states会是["1", "1"] fmt.Println(states) // 遍历切片处理每个值 for _, s := range states { // 自定义处理逻辑 } return c.SendString("Received states: " + strings.Join(states, ", ")) })
补充说明
c.FormValue("state")仅返回第一个匹配的参数值,而c.FormValues("state")会返回所有匹配的值,完美适配复选框这类可能提交多个同名参数的场景。- 你的表单代码存在一个小问题:所有
<label>的for属性都指向state,但每个<input>没有对应的唯一id,建议给每个复选框设置唯一id并让label的for属性对应,避免点击标签时无法正确触发复选框:
<form method="post" action="/providers"> <input type="checkbox" name="state" value="1" id="state1"><label for="state1">Provider1</label> <input type="checkbox" name="state" value="0" id="state2"><label for="state2">Provider2</label> <input type="checkbox" name="state" value="1" id="state3"><label for="state3">Provider3</label> </form>
内容的提问来源于stack exchange,提问作者Petr Lozovitskii
相关产品推荐
相关产品推荐

