<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<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="login">
</div>
</form>
</body>
</html>
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
type info struct {
Username string `json:"username"`
Password string `json:"password"`
}
func login(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "login.html", nil)
}
func loginPost(ctx *gin.Context){
username ,ok := ctx.GetPostForm("username")
if !ok{
username = "marshmallow" // 如果username 不存在则将username设置为marshmallow
}
password ,ok := ctx.GetPostForm("password")
if !ok{
password = "************"
}
userInfo := info{
//Username: ctx.PostForm("username"),
//Password: ctx.PostForm("password"),
//Username: ctx.DefaultPostForm("username","marshmallow"), // 如果username 不存在则将username设置为marshmallow
//Password: ctx.DefaultPostForm("password","************"),
Username: username,
Password: password,
}
ctx.JSON(http.StatusOK, userInfo)
}
func main() {
r := gin.Default()
r.LoadHTMLFiles("./login.html")
r.GET("/login", login)
r.POST("/login",loginPost)
err := r.Run(":8080")
if err != nil {
fmt.Println(err)
return
}
}
Gin获取Form表单数据