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

 更新时间:2023年3月10日 16:34  点击:597 作者:HSMgogogo!

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请求内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://blog.csdn.net/scuff/article/details/124308575

[!--infotagslink--]

相关文章