test.go:
package main
import "github.com/gin-gonic/gin"
type User struct {
Username string `form:"username"`
Password string `form:"password"`
Hobby []string `form:"hobby"`
Gender string `form:"gender"`
City string `form:"city"`
// 注意此处标签是 form
}
func GoRegister(c *gin.Context) {
c.HTML(200, "register.html", nil)
}
func Register(c *gin.Context) {
var user User
c.ShouldBind(&user)
c.String(200, "User: %s", user)
}
func main() {
e := gin.Default()
e.LoadHTMLGlob("templates/*")
e.POST("/register", Register)
e.GET("/register", GoRegister)
e.Run()
}
templates\register.html:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>用户注册title>
head>
<body>
<h1>用户注册页面h1>
<form action="/register" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
爱好:
<input type="checkbox" name="hobby" value="swiming">游泳
<input type="checkbox" name="hobby" value="football">足球
<input type="checkbox" name="hobby" value="basketball">篮球
<input type="checkbox" name="hobby" value="sing">唱歌
<br>
性别:
<input type="radio" name="gender" value="male">男
<input type="radio" name="gender" value="female">女
<br>
城市:
<select name="city">
<option value="beijing">北京option>
<option value="shanghai">上海option>
<option value="chengdu">成都option>
select>
<br>
<input type="submit" value="注册">
form>
body>
html>
浏览器输入:localhost:8080/register
页面显示:
填入表单信息后点击注册:
package main
import (
"log"
"github.com/gin-gonic/gin"
)
type User struct {
Username string `form:"username"`
Password string `form:"password"`
// 注意此处标签还是 form
}
func TestGetBind(c *gin.Context) {
var user User
err := c.ShouldBind(&user)
if err != nil {
log.Fatal(err)
}
c.String(200, "User:%s", user)
}
func main() {
e := gin.Default()
e.GET("/testGetBind", TestGetBind)
e.Run()
}
浏览器输入:localhost:8080/testGetBind
页面显示为:
将url更改为:localhost:8080/testGetBind?username=Psych&password=666
页面显示为:
package main
import (
"log"
"github.com/gin-gonic/gin"
)
type User struct {
Username string `uri:"username"`
Password string `uri:"password"`
// 注意此处标签为 uri
}
func TestGetBind(c *gin.Context) {
var user User
err := c.ShouldBindUri(&user)
if err != nil {
log.Fatal(err)
}
c.String(200, "User:%s", user)
}
func main() {
e := gin.Default()
e.GET("/testGetBind/:username/:password", TestGetBind) // localhost:8080/testGetBind/Psych/666
e.Run()
}
浏览器输入:localhost:8080/testGetBind/Psych/666
页面显示为: