Gin框架獲取form參數


Gin框架獲取form參數

登錄界面

<!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="password" name="password" , id="password">
    </div>
    <div>
        <input type="submit" value="登錄">

    </div>
</form>
</body>
</html>

image-20211116230634018

一、PostForm方式

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {

	r := gin.Default()
	r.LoadHTMLFiles("../templates/login.html")
	// 獲取form表單提交數據
	r.GET("/login", func(c *gin.Context) {
		c.HTML(http.StatusOK, "login.html", nil)

	})
	// 獲取數據
	r.POST("/login", func(c *gin.Context) {
		// 方式一
		username := c.PostForm("username")
		password := c.PostForm("password")


		c.JSON(http.StatusOK, gin.H{
			"username": username,
			"password": password,
		})

	})
	r.Run(":9999")
}

image-20211116230611418

二、DefaultPostForm方式

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {

	r := gin.Default()
	r.LoadHTMLFiles("../templates/login.html")
	// 獲取form表單提交數據
	r.GET("/login", func(c *gin.Context) {
		c.HTML(http.StatusOK, "login.html", nil)

	})
	// 獲取數據
	r.POST("/login", func(c *gin.Context) {
		
		// 方式二
		username := c.DefaultPostForm("username", "body") // 取不到key,則值為默認值body
		password := c.DefaultQuery("password", "123")

		c.JSON(http.StatusOK, gin.H{
			"username": username,
			"password": password,
		})

	})
	r.Run(":9999")
}

image-20211116230615575

三、GetPostForm方式

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {

	r := gin.Default()
	r.LoadHTMLFiles("../templates/login.html")
	// 獲取form表單提交數據
	r.GET("/login", func(c *gin.Context) {
		c.HTML(http.StatusOK, "login.html", nil)

	})
	// 獲取數據
	r.POST("/login", func(c *gin.Context) {
	
		// 方式三
		username, ok := c.GetPostForm("username")
		if !ok {
			username = "body"
		}

		password, ok := c.GetPostForm("password")
		if !ok {
			password = "sdfsdf"
		}
		c.JSON(http.StatusOK, gin.H{
			"username": username,
			"password": password,
		})

	})
	r.Run(":9999")
}

image-20211116230621090


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM