如何在Golang中使用gin框架获取HTTP POST请求的原始数据

huangapple go评论89阅读模式
英文:

How to get raw data of http post request inn Golang using gin framework

问题

我在服务器上收到一个POST请求,其负载如下所示:

{
    "amount": 10000,
    "amount_due": 0,
    "amount_paid": 10000,
    "attempts": 1
}

内容类型为application/json。现在,为了进行一些计算,我希望将该负载转换为原始文本,如下所示:

{"amount":10000,"amount_due":0,"amount_paid":10000,"attempts":1}
没有空格和换行符

我正在使用Golang和gin框架,但是当我尝试获取请求体时,使用了ginCtx *gin.Context.Request.Body或ginCtx *gin.Context.GetRawData(),我没有得到我真正想要的原始数据,而是得到了格式良好的缩进json,但我想要的是原始请求体。请帮助我使用gin框架在Golang中如何获取原始请求体。

英文:

I am getting one POST request in my server whose payload is something like that

{       "amount": 10000,
        "amount_due": 0,
        "amount_paid": 10000,
        "attempts": 1,
}

and content-type is application/json.
Now for some calculation I want that payload in raw text something like that.

{"amount":10000,"amount_due":0,"amount_paid":10000,"attempts":1} 
No space and no new line

I am using Golang and gin framework, but which I am trying to get the request body like
ginCtx *gin.Context.Request.Body or ginCtx *gin.Context.GetRawData(), then I am not getting my actual desired raw data, I am getting well indented json, but I want raw body.
Please help me how to get that in Golang using gin framework.

答案1

得分: 2

请注意,raw表示未经处理的数据,这正是c.GetRawData()返回的内容。

如果你想获取原始数据并删除所有无关的空格,那么你需要对数据进行处理。处理后的结果,根据定义,将不再是原始数据

所以你的问题不太清楚。

  • 你想要原始数据吗?那么请使用c.GetRawData()
  • 你想要删除无关空格的数据吗?那么请使用json.Compact
raw, err := c.GetRawData()
if err != nil {
    return err
}
var buf bytes.Buffer
if err := json.Compact(&buf, raw); err != nil {
    return err
}
data := buf.Bytes()
fmt.Println(string(data))
英文:

> but I want raw body

Note that raw means unprocessed, which is exactly what c.GetRawData() returns.

If you want to take the raw data and remove all insignificant whitespace then you need to process the data. The result of that processing, by definition, will not be raw data anymore.

So it is not very clear what you are asking for.

raw, err := c.GetRawData()
if err != nil {
    return err
}
var buf bytes.Buffer
if err := json.Compact(&buf, raw); err != nil {
    return err
}
data := buf.Bytes()
fmt.Println(string(data))

huangapple
  • 本文由 发表于 2022年11月4日 01:51:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/74307510.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定