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

其他教程   发布日期:2023年08月11日   浏览次数:207

这篇文章主要讲解了“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请求参数如何处理的资料请关注九品源码其它相关文章!