关于gin框架中传参的案例

get请求

地址栏用/拼接 地址栏用/拼接

请求地址:http://localhost:8080/user/info/222/charlie
gin框架定义:

//在代码中定义接收参数:/:id/:name
user.GET("/info/:id/:name", controllers.UserStruct{}.GetUserInfo)
func (u UserStruct) GetUserInfo(c *gin.Context) {
	//然后在c中获取id和name
	id := c.Param("id")
	name := c.Param("name")
	ReturnSuccess(c, 200, "success", id+"-"+name, 1)
}

Post表单提交

请求地址:http://localhost:8080/order/list?id=1
gin框架定义:

//在代码中定义接收参数:/list
order.POST("/list", controllers.OrderStruct{}.GetOrderList)
func (o OrderStruct) GetOrderList(c *gin.Context) {
	//然后在c中获取id
	id := c.PostForm("id")

	//如果前端没有传入name,则给个默认值
	name := c.DefaultPostForm("name", "charlie")
	ReturnSuccess(c, 200, "order list success", id+"-"+name, 10)
}

Post body传参

方式一:使用map接收body体中的数据

请求地址:http://localhost:8080/user/list
gin框架定义:

//在代码中定义接收参数:/list
user.POST("/list", controllers.UserStruct{}.GetUserList)
//然后在c中获取id和name
func (u UserStruct) GetUserList(c *gin.Context) {
	param := make(map[string]interface{})
	err := c.BindJSON(&param)
	if err == nil {
		ReturnSuccess(c, 200, param["name"], param["id"], 0)
		return
	}
	ReturnError(c, 500, "not fund user list")
}

方式二:定义strcut接收body体中的数据

请求地址:http://localhost:8080/user/list
gin框架定义:

//定义结构体
type QueryListStruct struct {
	Name string `json:"name"`
	Id   int    `json:"id"`
}

func (u UserStruct) GetUserList(c *gin.Context) {
	//创建一个指针类型的结构体变量
	query := &QueryListStruct{}
	//&query是一个指向QueryListStruct的指针
	// 为什么要用指针?因为 Go 的反射机制需要通过指针修改结构体字段的值,能正确绑定 JSON 数据到结构体字段。
	//会将c中接收的值赋值给query指向的结构体字段。
	err := c.BindJSON(&query)
	if err == nil {
		ReturnSuccess(c, 200, query.Name, query.Id, 0)
		return
	}
	fmt.Println(err)
	ReturnError(c, 500, "not fund user list")
}
posted @ 2025-07-17 17:01  Charlie-Pang  阅读(14)  评论(0)    收藏  举报