Gin框架 获取请求参数 - Go语言中文社区

Gin框架 获取请求参数


获取GET请求参数

func main() {
	router := gin.Default()

	// Query string parameters are parsed using the existing underlying request object.
	// The request responds to a url matching:  /welcome?firstname=Jane&lastname=Doe
	router.GET("/welcome", func(c *gin.Context) {
     	//查询请求URL后面的参数,如果没有填写默认值
		firstname := c.DefaultQuery("firstname", "Guest")
		//查询请求URL后面的参数
		lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")

		c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
	})
	router.Run(":8080")
}

如下图请求方式以键的形式和路径进行拼接

在这里插入图片描述

获取POST请求参数

func main() {
	router := gin.Default()

	router.POST("/form_post", func(c *gin.Context) {
	  //从表单中查询参数
		message := c.PostForm("message")
		 //从表单中查询参数,,如果没有就获取默认值
		nick := c.DefaultPostForm("nick", "anonymous")

		c.JSON(200, gin.H{
			"status":  "posted",
			"message": message,
			"nick":    nick,
		})
	})
	router.Run(":8080")
}

如下图请求方式以键的形式和路径进行拼接

在这里插入图片描述

获取Body值

package main

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

func main() {
	router := gin.Default()
	
	router.POST("/user/*action", func(c *gin.Context) {
		bodyBytes, _ := ioutil.ReadAll(c.Request.Body)
		c.String(http.StatusOK, string(bodyBytes))
	})
	router.Run(":8080")
}

获取路径中的参数

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)
func main() {
	router := gin.Default()

	// 此规则能够匹配/user/john这种格式,但不能匹配/user/ 或 /user这种格式
	router.GET("/user/:name", func(c *gin.Context) {
	    //从表单中查询参数
		name := c.Param("name")
		c.String(http.StatusOK, "Hello %s", name)
	})

	// 但是,这个规则既能匹配/user/john/格式也能匹配/user/john/send这种格式
	// 如果没有其他路由器匹配/user/john,它将重定向到/user/john/
	router.GET("/user/:name/*action", func(c *gin.Context) {
		name := c.Param("name")
		action := c.Param("action")
		message := name + " is " + action
		c.String(http.StatusOK, message)

	})

	router.Run(":8080")
}


请求方式如下图

在这里插入图片描述
未完待续~

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_44014995/article/details/108340915
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢