gin绑定前端传过来的数组
时间: 2023-09-16 09:11:59 浏览: 79
在gin框架中,可以使用`form`标签来绑定前端传过来的数组参数。具体步骤如下:
1. 定义一个结构体,用于接收数组参数:
```go
type ArrayParam struct {
Values []string `form:"values[]"`
}
```
2. 在路由处理函数中,使用`ShouldBind`方法将请求中的参数绑定到结构体中:
```go
func handler(c *gin.Context) {
var param ArrayParam
if err := c.ShouldBind(¶m); err != nil {
// 绑定出错,处理错误
return
}
// 处理数组参数
values := param.Values
// ...
}
```
3. 在前端,以`values[]`作为参数名,将多个值传递给数组参数:
```html
<form action="/path" method="post">
<input type="text" name="values[]" value="value1">
<input type="text" name="values[]" value="value2">
<input type="text" name="values[]" value="value3">
<button type="submit">Submit</button>
</form>
```
这样就可以在gin框架中绑定前端传过来的数组了。
相关推荐
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)