gin作为go语言最知名的网络库,在这里我简要介绍一下url的查询参数解析。主要是这里面存在一些需要注意的地方。这里,直接给出代码,和运行结果,在必要的地方进行分析。
代码1:
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"` } func GetDataB(c *gin.Context) { var b StructB c.Bind(&b) c.JSON(200, gin.H{ "a": b.NestedStruct, "b": b.FieldB, }) } func GetDataC(c *gin.Context) { var b StructC c.Bind(&b) c.JSON(200, gin.H{ "a": b.NestedStructPointer, "c": b.FieldC, }) } func main() { r := gin.Default() r.GET("/getb", GetDataB) r.GET("/getc", GetDataC) r.Run() }
测试结果:
$ curl "http://localhost:8080/getb?field_a=hello&field_b=world" {"a":{"FieldA":"hello"},"b":"world"} $ curl "http://localhost:8080/getc?field_a=hello&field_c=world" {"a":{"FieldA":"hello"},"c":"world"}
上述结果显示gin的query解析可以嵌套赋值,只需要form tag和传入的参数一致。
再看下面的代码:
代码2:
package main import ( "github.com/gin-gonic/gin" ) type StructA struct { FieldA string `form:"field_a"` } type StructB struct { StructA FieldB string `form:"field_b"` } type StructC struct { *StructA FieldC string `form:"field_c"` } func GetDataB(c *gin.Context) { var b StructB c.Bind(&b) c.JSON(200, gin.H{ "a": b.FieldA, "b": b.FieldB, }) } func GetDataC(c *gin.Context) { var b StructC c.Bind(&b) c.JSON(200, gin.H{ "a": b.FieldA, "c": b.FieldC, }) } func main() { r := gin.Default() r.GET("/getb", GetDataB) r.GET("/getc", GetDataC) r.Run() }
输出结果:
curl "http://localhost:8080/getb?field_a=hello&field_b=world"
{"a":"hello","b":"world"}
curl "http://localhost:8080/getc?field_a=hello&field_c=world"
{"a":"hello","c":"world"}
结果显示,gin的url查询参数解析可以正常处理嵌套的结构体,只需要form tag和传入的参数一致。
再看下面代码:
代码3:
package main import ( "github.com/gin-gonic/gin" ) type structA struct { FieldA string `form:"field_a"` } type StructB struct { structA FieldB string `form:"field_b"` } type StructC struct { *structA FieldC string `form:"field_c"` } func GetDataB(c *gin.Context) { var b StructB c.Bind(&b) c.JSON(200, gin.H{ "a": b.FieldA, "b": b.FieldB, }) } func GetDataC(c *gin.Context) { var b StructC c.Bind(&b) c.JSON(200, gin.H{ "a": b.FieldA, "c": b.FieldC, }) } func main() { r := gin.Default() r.GET("/getb", GetDataB) r.GET("/getc", GetDataC) r.Run() }
注意,上述代码只是将StructA改为structA,也就是说大小写变化。测试结果如下:
curl "http://localhost:8080/getb?field_a=h