编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

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

wxchong 2024-07-25 13:32:22 开源技术 19 ℃ 0 评论

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

1、获取Get请求参数

获取请求 url 示例:http://127.0.0.1/path?user=admin

获取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路径参数

示例地址:http://127.0.0.1:80/path/admin

获取 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参数优先级最高

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表