设为首页 加入收藏

TOP

gin的url查询参数解析(一)
2019-05-23 14:36:17 】 浏览:277
Tags:gin url 查询 参数 解析

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

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇go流程控制 下一篇Golang实现requests库

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目