gin中绑定表单数据至自定义结构体

package main

import "github.com/gin-gonic/gin"

type StructA struct {
	FieldA string `form:"field_a"`
}
type StructB struct {
	// 嵌套结构体
	NestedStruct StructA
	FieldB string `form:"field_b"`
}
type StructC struct {
	// 嵌套结构体指针
	NestedStructPointer *StructA
	FieldC string `form:"field_c"`
}
type StructD struct {
	// 嵌套匿名结构体
	NestedAnonymousStruct struct{
		FieldX string `form:"field_x"`
	}
	FieldD string `form:"field_d"`
}

func GetB(c *gin.Context) {
	// 绑定表单数据至自定义结构体
	var b StructB
	c.Bind(&b)
	c.JSON(200, gin.H{"field_a": b.NestedStruct, "field_b": b.FieldB})
}
func GetC(c *gin.Context) {
	var cc StructC
	c.Bind(&cc)
	c.JSON(200, map[string]interface{}{"field_a": cc.NestedStructPointer, "field_c": cc.FieldC})
}
func GetD(c *gin.Context) {
	var d StructD
	c.Bind(&d)
	c.JSON(200, gin.H{"field_x": d.NestedAnonymousStruct, "field_d": d.FieldD})
}

func main() {
	r := gin.Default()
	r.GET("/getb", GetB)
	r.GET("/getc", GetC)
	r.GET("/getd", GetD)
	r.Run()
}

  

请求方法:

http://127.0.0.1:3000/getd?field_a=aaa&field_b=bbbb

http://127.0.0.1:3000/getd?field_a=aaa&field_c=ccccc

http://127.0.0.1:3000/getd?field_d=ddddd&field_x=xxxxxxxx

posted @ 2021-10-27 18:18  专职  阅读(389)  评论(0编辑  收藏  举报