how to bind multiple same parameter like this to object:
api/report/tripexcelmulti2?ids[]=2235&ids[]=3509&ids[]=4080&nopols[]=MUJI%20(BUS)&nopols[]=APRIYANDI%20(CAR)&nopols[]=JUNEDI%20(CAR%20POLICE)&fdate=2022-07-11%2000:00&tdate=2022-07-11%2023:59
Comment From: eleven26
If it is an array, you can define a struct
, which defines the corresponding array field, and then the field name is in the form of ids[]
. Note that you need to include square brackets, and then write the validation rules in the binding
tag. Use dive
to validate each item in the array is meet your needs.
package main
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
)
type TestStruct struct {
// This is what you want...
Ids []int `form:"ids[]" binding:"dive,numeric,gt=0"`
}
func test(c *gin.Context) {
var testStruct TestStruct
if c.ShouldBindQuery(&testStruct) == nil {
log.Println(testStruct.Ids)
c.String(http.StatusOK, "Success")
return
}
c.String(http.StatusBadRequest, "Failed")
return
}
func main() {
route := gin.Default()
route.Any("/test", test)
route.Run(":8085")
}
The most important thing is this line:
Ids []int `form:"ids[]" binding:"dive,numeric,gt=0"`
For specific usage, please refer to:
validator binding-and-validation
Comment From: centratelemedia
hi @eleven26
Thank you so much...