Gin框架获取表单参数的几种方式
Gin框架获取表单参数的几种方式:
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.Static("/static", "./static")
r.LoadHTMLFiles("./index.html", "./login.html")
r.GET("/login", func(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "login.html", nil)
})
r.POST("/login", func(c *gin.Context) {
// 获取form表单提交的数据 1:
// username := c.PostForm("username")
// password := c.PostForm("password") // 取到就返回值,取不到返回空字符串
// 2:
//username := c.DefaultPostForm("username", "somebody")
//password := c.DefaultPostForm("xxx", "***")
// 3: 这里一定要看下面注意事项⚠️
username, ok := c.GetPostForm("username")
if !ok {
username = "Default username"
}
password, ok := c.GetPostForm("password")
if !ok {
password = "Default ***"
}
c.HTML(http.StatusOK, "index.html", gin.H{
"username": username,
"password": password,
})
})
r.Run(":8088")
}
要注意GetPostForm()的使用:
// For example, during a PATCH request to update the user's email:
// email=mail@example.com --> ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com"
// email= --> ("", true) := GetPostForm("email") // set email to ""
// --> ("", false) := GetPostForm("email") // do nothing with email
简单的登录窗口:
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<!-- form 表单 action:submit后的动作,动作对应的方法-->
<form action="/login" method="post" novalidate autocomplete="off">
<div>
<label for="username">username:</label>
<input type="text" name="username" id="username">
</div>
<div>
<label for="password">password:</label>
<input type="password" name="password" id="password">
</div>
<div>
<input type="submit" value="登录">
</div>
</form>
</body>
</html>