gin架構23--綁定 HTML 複選框
- 介紹
- 案例
- 說明
介紹
本文通過一個簡單的案例,将結構體和html中的 form 資料綁定在一起。
案例
源碼:
main.go
package main
import (
"github.com/gin-gonic/gin"
)
type myForm struct {
Colors []string `form:"colors[]"`
}
func main() {
r := gin.Default()
r.LoadHTMLGlob("views/*")
r.GET("/", indexHandler)
r.POST("/", formHandler)
r.Run(":8080")
}
func indexHandler(c *gin.Context) {
c.HTML(200, "form.html", nil)
}
func formHandler(c *gin.Context) {
var fakeForm myForm
c.Bind(&fakeForm)
c.JSON(200, gin.H{"color": fakeForm.Colors})
}
views/form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>gin23</title>
</head>
<body>
<form action="/" 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>
測試:
$ tree -L 2
.