Gin 使用示例(三):绑定 HTML 复选框 checkbox


HTML 模板

src/gin-demo/examples/templates/checkbox/color.tmpl

{{ define "checkbox/color.tmpl" }}
<html>
  <h1>
    {{ .title }}
  </h1>
  <form action="/colors" method="POST">
    <p>选择颜色</p>
    <label for="red">红</label>
    <input type="checkbox" name="colors[]" value="red" id="red">
    <label for="green">绿</label>
    <input type="checkbox" name="colors[]" value="green" id="green">
    <label for="blue">蓝</label>
    <input type="checkbox" name="colors[]" value="blue" id="blue">
    <input type="submit" value="提交">
  </form>
</html>
{{ end }}

服务器路由

src/gin-demo/examples/html_checkbox.go

package main

import (
  "github.com/gin-gonic/gin"
  "net/http"
)

type myForm struct {
  Colors []string `form:"colors[]"`
}

func main()  {
  r := gin.Default()
  r.LoadHTMLGlob("templates/**/*")
  r.GET("/colors", func(c *gin.Context) {
    c.HTML(http.StatusOK, "checkbox/color.tmpl", gin.H{
      "title": "Select Colors",
    })
  })
  r.POST("/colors", func(c *gin.Context) {
    var fakeForm myForm
    // ShouldBind 和 Bind 类似,不过会在出错时退出而不是返回400状态码
    c.ShouldBind(&fakeForm)
    c.JSON(200, gin.H{"color": fakeForm.Colors})
  })
  r.Run()
}

测试

启动服务器:

-w883

在浏览器中访问页面 http://localhost:8080/colors

-w676

选择颜色提交后:

-w663


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Gin 使用示例(二):通过自定义结构体绑定表单请求数据

>> 下一篇: Gin 使用示例(四):绑定查询字符串或 POST 数据