模拟简单登录页面:

- html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
-
- <title>logintitle>
- 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的返回页面:

- "en">
-
- "UTF-8">
-
-
index -
-
Hello , {{ .Name }}!
-
你的密码是 : {{ .Password }}
-
-
获取方法一代码:
- 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")
- }