英文:
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.
- Do you want raw data? Then use
c.GetRawData()
. - Do you want data with insignificant whitespace removed? Then use
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论