go gin form 表单验证 仅做记录
main.gopackage mainimport ("fmt""github.com/xiuno/gin""html/template""net/http""time")func formatAsDate(t time.Time) string {year, month, day := t.Date()return fmt.Sprintf("%...
·
main.go
package main
import (
"fmt"
"github.com/xiuno/gin"
"html/template"
"net/http"
"time"
)
func formatAsDate(t time.Time) string {
year, month, day := t.Date()
return fmt.Sprintf("%d%02d/%02d", year, month, day)
}
// type Person struct {
// ID string `uri:"id" binding:"required,uuid"`
// Name string `uri:"name" binding:"required"`
// }
type myForm struct {
Colors []string `form:"colors[]"`
}
func formHandler(c *gin.Context) {
var fakeForm myForm
c.ShouldBind(&fakeForm)
c.JSON(200, gin.H{"color":fakeForm.Colors})
}
func main() {
r := gin.Default()
// r.GET("/:name/:id", func(c *gin.Context) {
// var person Person
// if err := c.ShouldBindUri(&person); err != err {
// c.JSON(400, gin.H{"msg":err})
// return
// }
// c.JSON(200, gin.H{"name":person.Name, "uuid": person.ID})
// })
// r.Delims("{[{", "}]}") //您可以使用自定义delims
r.SetFuncMap(template.FuncMap{
"formatAsDate": formatAsDate,
})
r.LoadHTMLGlob("view/*")
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{
"now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),
"title": "hello Go",
})
})
r.POST("/", formHandler)
r.Run()
}
view/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>{{ .title }}</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>
更多推荐
已为社区贡献2条内容
所有评论(0)