golang接收post和get请求参数如何处理

这篇文章主要讲解了“golang接收post和get请求参数如何处理”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“golang接收post和get请求参数如何处理”吧!

1、golang中获取请求接口中数据(GET)

方式一: API参数 ctx.Param(name string)或者ctx.Params.ByName(name string)

前端请求为:

"http://localhost:8080/api/book/paging/"+this.pageNum+"/"+this.pageSize
//形式为:"http://localhost:8080/api/book/paging/2/2

此时后端路由写为:

r.GET("/api/book/paging/:page_num/:page_size",controller.Paging)

后端接收路径中参数:

pageSize,_:=strconv.Atoi(ctx.Param("page_size"))//它是下面的简写
pageNum,_:=strconv.Atoi(ctx.Params.ByName("page_num"))

方式二:URL参数 ctx.Query(name string)

前端请求为:

"http://localhost:8080/api/book/paging?page_num="+this.pageNum+"&page_size="+this.pageSize
//形式为:"http://localhost:8080/api/book/paging?page_num=2&page_size=2

此时后端路由写为:

r.GET("/api/book/paging",controller.Paging)

后端接收路径中参数:

pageSize,_:=strconv.Atoi(ctx.Query("page_size"))
pageNum,_:=strconv.Atoi(ctx.Query("page_num"))

2、golang中获取请求接口中数据(POST)

方式1:

    var requestUser=model.User{}
    _=ctx.Bind(&requestUser)
    //获取参数
    telephone:=requestUser.Telephone
    password:=requestUser.Password

方式2:

    //使用map获取请求的参数
    var requestMap=make(map[string]string)
    _ = json.NewDecoder(ctx.Request.Body).Decode(&requestMap)

方式3:

    var requestRegister=model.User{}
    json.NewDecoder(ctx.Request.Body).Decode(&requestRegister)

感谢各位的阅读,以上就是“golang接收post和get请求参数如何处理”的内容了,经过本文的学习后,相信大家对golang接收post和get请求参数如何处理这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程之家,小编将为大家推送更多相关知识点的文章,欢迎关注!

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1 Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...