Gin 獲取參數(shù)

2023-03-22 15:32 更新

獲取Query參數(shù)

在Gin框架中,可以通過(guò)Query來(lái)獲取URL中?后面所攜帶的參數(shù)。例如?/name=admin&pwd=123456?。獲取方法如下

package main

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

func main() {
	r := gin.Default()
	r.GET("/", func(c *gin.Context) {
		name := c.Query("name")
		pwd := c.Query("pwd")
		// fmt.Printf("name:%s ; pwd:%s",name,pwd)
		c.JSON(http.StatusOK, gin.H{
			"name": name,
			"pwd":  pwd,
		})
	})
	r.Run()
}

獲取Form參數(shù)

當(dāng)前端請(qǐng)求的數(shù)據(jù)通過(guò)form表單提交時(shí),例如向?/user/reset?發(fā)送了一個(gè)POST請(qǐng)求,獲取請(qǐng)求數(shù)據(jù)方法如下

package main

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

func main() {
	r := gin.Default()
	r.LoadHTMLFiles("./login.html", "./index.html") //加載頁(yè)面
	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "login.html", nil)

	})
	r.POST("/", func(c *gin.Context) {
		username := c.PostForm("username") //對(duì)應(yīng)h5表單中的name字段
		password := c.PostForm("password")
		c.HTML(http.StatusOK, "index.html", gin.H{
			"username": username,
			"password": password,
		})
	})
	r.Run()
}

獲取Path參數(shù)

請(qǐng)求的參數(shù)通過(guò)URL路徑傳遞,例如?/user/admin?,獲取請(qǐng)求URL路徑中的參數(shù)方法如下

package main

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

func main() {
	r := gin.Default()
	r.GET("/user/:username", func(c *gin.Context) {
		username := c.Param("username")
		c.JSON(http.StatusOK, gin.H{
			"username": username,
		})
	})
	r.Run()
}


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)