go學習-獲取form表單提交數據


當前端請求的數據通過form表單提交時,例如向/user/search發送一個POST請求,獲取請求數據的方式如下:
main.go

package main

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)
	})

	r.POST("/login", func(c *gin.Context) {
		//方法1 用PostForm獲取form表達
		// username := c.PostForm("username")
		// password := c.PostForm("password")
		//方法2 用DefaultPostForm獲取form表達,有個默認值
		// username := c.DefaultPostForm("username", "默認名字")
		// password := c.DefaultPostForm("password", "默認密碼")
		//方法3 GetPostForm 多了一個是否存在的返回值
		username, ok := c.GetPostForm("username")
		if !ok {
			username = "默認用戶名"
		}
		password, ok := c.GetPostForm("password")
		if !ok {
			password = "默認密碼"
		}
		c.HTML(http.StatusOK, "index.html", gin.H{
			"name":     username,
			"Password": password,
		})
	})
	r.Run(":9090")
}

login.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>index</title>
</head>
<body>
    <p>你的名字是:{{ .name }}</p>
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>index</title>
</head>
<body>
    <p>你的名字是:{{ .name }}</p>
</body>
</html>

編譯后頁面
初期進行get請求

輸入用戶名密碼,點擊登錄,進行post請求


免責聲明!

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



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