dt250827 2015-08-10 04:20
浏览 50
已采纳

杜松子酒/ golang-空需求体

I'm new to Go and Gin, and am having trouble printing out the full request body.

I want to be able to read the request body from third party POST, but I'm getting empty request body

curl -u dumbuser:dumbuserpassword -H "Content-Type: application/json" -X POST --data '{"events": "3"}' http://localhost:8080/events

My entire code is as below. Any pointer is appreciated!

package main

import (
  "net/http"
  "fmt"
  "github.com/gin-gonic/gin"
)

func main() {
  router := gin.Default()
  authorized := router.Group("/", gin.BasicAuth(gin.Accounts{
     "dumbuser": "dumbuserpassword",
  }))
  authorized.POST("/events", events)
  router.Run(":8080")
}

func events(c *gin.Context) {
  fmt.Printf("%s", c.Request.Body)
  c.JSON(http.StatusOK, c)
}
  • 写回答

1条回答 默认 最新

  • dsfykqq3403 2015-08-10 05:35
    关注

    The problem here is that you're printing out the string value of c.Request.Body, which is of interface type ReadCloser.

    What you can do to satisfy yourself that it does in fact contain the body you want is to read the value out of c.Request.Body to a string, and then print that out. This is for your learning process only!

    Learning code:

    func events(c *gin.Context) {
            x, _ := ioutil.ReadAll(c.Request.Body)
            fmt.Printf("%s", string(x))
            c.JSON(http.StatusOK, c)
    }
    

    However, this is not the way you should access the body of the request. Let gin do the parsing of the body for you, by using a binding.

    More correct code:

    type E struct {
            Events string
    }
    
    func events(c *gin.Context) {
            data := &E{}
            c.Bind(data)
            fmt.Println(data)
            c.JSON(http.StatusOK, c)
    }
    

    This is a more correct way to access the data in the body, since it will be already parsed out for you. Note that if you read the body first, as we did above in the learning step, the c.Request.Body will have been emptied, and so there will be nothing left in the body for Gin to read.

    Broken code:

    func events(c *gin.Context) {
        x, _ := ioutil.ReadAll(c.Request.Body)
        fmt.Printf("%s", string(x))
        data := &E{}
        c.Bind(data) // data is left unchanged because c.Request.Body has been used up.
        fmt.Println(data)
        c.JSON(http.StatusOK, c)
    }
    

    You're probably also curious why the JSON returned from this endpoint shows and empty Request.Body. This is for the same reason. The JSON Marshalling method cannot serialize a ReadCloser, and so it shows up as empty.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型