gin获取表单from中的数据
模拟简单登录页面:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>login</title>
</head><body><form action="/login" method="post"><div><label for="username">username:</label><input type="text" name="username" id="username"></div><div><label for="password">password:</label><input type="text" name="password" id="password"></div><div>//当submit被点击以后,会向服务端发送请求,发送方式为post<input type="submit" value="登录"></div></form></body></html>
对于POST的返回页面:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>index</title>
</head><body><h1>Hello , {{ .Name }}!</h1><h1>你的密码是 : {{ .Password }}</h1></body></html>
获取方法一代码:
package main//from表单提交的参数
import ("net/http""github.com/gin-gonic/gin"
)func main() {r := gin.Default()r.LoadHTMLFiles("./login.html", "./index.html")r.GET("/login", func(c *gin.Context) {c.HTML(http.StatusOK, "login.html", nil)})//POST请求r.POST("/login", func(c *gin.Context) {username := c.PostForm("username")password := c.PostForm("password")c.HTML(http.StatusOK, "index.html", gin.H{"Name": username,"Password": password,})})r.Run(":9090")
}
获取方法二代码:
带默认值
package main//from表单提交的参数
import ("net/http""github.com/gin-gonic/gin"
)func main() {r := gin.Default()r.LoadHTMLFiles("./login.html", "./index.html")r.GET("/login", func(c *gin.Context) {c.HTML(http.StatusOK, "login.html", nil)})//POST请求r.POST("/login", func(c *gin.Context) {// username := c.PostForm("username")// password := c.PostForm("password")username := c.DefaultPostForm("username", "somebody")password := c.DefaultPostForm("password", "*******")c.HTML(http.StatusOK, "index.html", gin.H{"Name": username,"Password": password,})})r.Run(":9090")
}
方法三:GetPostFrom
package main//from表单提交的参数
import ("net/http""github.com/gin-gonic/gin"
)func main() {r := gin.Default()r.LoadHTMLFiles("./login.html", "./index.html")r.GET("/login", func(c *gin.Context) {c.HTML(http.StatusOK, "login.html", nil)})//POST请求r.POST("/login", func(c *gin.Context) {// username := c.PostForm("username")// password := c.PostForm("password")//username := c.DefaultPostForm("username", "somebody")//password := c.DefaultPostForm("password", "*******")username,ok := c.GetPostForm("username")if !ok {username = "sb"}password,ok := c.GetPostForm("password")if !ok {password = "******"}c.HTML(http.StatusOK, "index.html", gin.H{"Name": username,"Password": password,})})r.Run(":9090")
}