Gin处理Http请求的过程是通过路由将请求映射到相应的处理函数上.每个请求都会先经过中间件(如果有).然后处理函数会根据请求方法和路径执行相应的业务逻辑.

1.获取Get请求参数:

在Gin中可以通过url获取get请求参数主要有两种方式.

1.1查询参数:

客户端在发出get请求的时候可以在url中附带查询参数.Gin提供了gin.Context对象的Query方法来获取参数,如果参数不存在.可以使用DefaultQuery方法为参数设置默认值.

1.2demo:
func handleGetRequest(c *gin.Context) {
	//从url中获取参数.如果参数不存在使用默认值.
	c.DefaultQuery("name", "itbo")
	c.DefaultQuery("age", "20")
}
1.3get请求参数绑定到结构体:

Gin也允许使用ShouldBindQuery方法将查询的参数绑定到结构体上.

func handleGetRequest(c *gin.Context) {
	var customer Customer
	if err := c.ShouldBindQuery(&customer); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
}

type Customer struct {
	Name string `form:"name" binding:"required"`
	Age  int    `form:"age" binding:"required"`
}

2.获取Post请求参数

在Gin中.处理Post请求参数时需要从请求体中获取.根据请求正文的内容类型来使用不同的方法处理.特点如下:

检测内容类型:

Gin会自动检测请求头的Content-Type字段,并根据类型来处理数据.

处理表单数据:

如果请求体中包含表单数据.则可以使用gin.Context对象的PostForm方法来获取值.

func handleFormPost(c *gin.Context) {
	name := c.PostForm("name")
	age := c.PostForm("age")
}
2.1处理json数据:

如果请求中包含json数据直接绑定到结构体上.

type Customer struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func handlerJsonRequest(c *gin.Context) {
	var customer Customer

	if err := c.ShouldBindJSON(&customer); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
}
2.2处理xml数据:

如果请求体中包含xml数据,可以使用ShouldBindXml方法绑定到结构体上.

type Customer struct {
	Name string `xml:"name"`
	Age  int    `xml:"age"`
}

func xmlHandlerRequest(c *gin.Context) {
	var customer Customer

	if err := c.ShouldBindXML(&customer); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

}
2.3请求数据绑定到结构体:

Gin支持直接把请求数据绑定到结构体上.不论类型是表单还是json xml.ShouldBind方法可以简化多个参数的处理过程.

type Customer struct {
	Name string `xml:"name" json:"name" form:"name" binding:"required"`
	Age  int    `xml:"age" json:"age" form:"age" binding:"required"`
}

func handlePost(c *gin.Context) {
	var customer Customer

	if err := c.ShouldBind(&customer); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
}
2.4验证结构体字段:

Gin支持通过结构体标签进行字段验证.例如:

type Customer struct {
	Name string `xml:"name" json:"name" form:"name" binding:"required"`
	Age  int    `xml:"age" json:"age" form:"age" binding:"gte=18,lte=25"`
}

 

每天坚持,终会如愿.

如果大家喜欢我的分享的话.可以关注我的微信公众号

念何架构之路

更多推荐