gin中绑定html复选框
main.go
package main import "github.com/gin-gonic/gin" type myForm struct { Colors []string `form:"colors[]"` } func main() { r := gin.Default() r.LoadHTMLFiles("templates/form.html") r.POST("/form", func(context *gin.Context) { var color myForm context.ShouldBind(&color) context.JSON(200, gin.H{ "color": color.Colors, }) }) r.GET("/", func(context *gin.Context) { context.HTML(200, "form.html", gin.H{}) }) r.Run() }
form.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/form" method="POST"> <p>Check some colors</p> <label for="red">Red</label> <input type="checkbox" name="colors[]" value="red" id="red"> <label for="green">Green</label> <input type="checkbox" name="colors[]" value="green" id="green"> <label for="blue">Blue</label> <input type="checkbox" name="colors[]" value="blue" id="blue"> <input type="submit"> </form> </body> </html>