您的位置 首页 golang

Go Web 框架 Gin 学习5 – 4种请求参数的处理

本章介绍 Gin 框架如何获取请求参数

1、获取Get请求参数

获取请求 url 示例:

获取Get请求参数的3个常用函数:

 func (c *Context) Query(key string) string  

根据key查询value,如果不存在,string为””

 func (c *Context) DefaultQuery(key, defaultValue string) string  

根据key查询value,如果不存在,返回defaultValue

 func (c *Context) GetQuery(key string) (string, bool)  

根据key查询value,如果不存在,返回bool为false,string为””

源码

执行结果

2、获取post请求参数

获取 Post 请求参数的常用函数:

 func (c *Context) PostForm(key string) string  

根据key查询value,如果不存在,string为””

 func (c *Context) DefaultPostForm(key, defaultValue string) string  

根据key查询value,如果不存在,返回defaultValue

 func (c *Context) GetPostForm(key string) (string, bool)  

根据key查询value,如果不存在,返回bool为false,string为””

源码

执行结果

3、获取URL路径参数

示例地址:

获取 URL 路径参数是指获取”/path/:name”类型的参数。本示例绑定参数name。

获取url路径参数的常用函数:

 func (c *Context) Param(key string) string  

根据key查询value,如果不存在,string为””

源码

执行结果

4、将请求参数绑定到struct对象

之前获取参数的方式是读取一个参数。对于支持 Get/Post 请求和正文内容为 json/xml 格式的 http 请求,Gin 框架可以将请求参数直接绑定到 struct 结构体。

 func (c *Context) ShouldBind(obj interface{}) error  

源码

注意:

(1)如果请求body通过http传递json格式的请求参数,通过post请求提交参数,需要将Content-Type设置为application/json,

(2)如果请求body通过http传递xml格式的请求参数,通过post请求提交参数,需要将Content-Type设置为application/xml,

(3)优先级:路由参数 < GET参数 < POST参数,如果同时存在路由参数、GET参数、POST参数,那么路由参数优先级最低,POST参数优先级最高

执行结果

执行结果

文章来源:智云一二三科技

文章标题:Go Web 框架 Gin 学习5 – 4种请求参数的处理

文章地址:https://www.zhihuclub.com/97609.shtml

关于作者: 智云科技

热门文章

网站地图