Go Lang – Gin : How to extract only the body (and ignore other garbage) from httputil.DumpRequest

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

Go Lang - Gin : How to extract only the body (and ignore other garbage) from httputil.DumpRequest

问题

我知道你可以通过ioutil.ReadAll(c.Request.Body)来获取请求体的内容。但是使用httputil.DumpRequest会返回包括其他值在内的请求信息,最后才是请求体的内容。

dump, err := httputil.DumpRequest(c.Request, true)

返回的结果如下:

> Content type: application/json IP: 127.0.0.1:36846 header token: Content length: 76 Request Method: POST Request URL: /signup Body:
POST /signup HTTP/1.1
Host: 127.0.0.1:8080
Accept: /
Accept-Encoding: gzip,deflate
Accept-Language: en-US,en;q=0.8
Connection: keep-alive
Content-Type: application/json
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.101 Safari/537.36
{"fname":"aFirstName", "lname":"aLName", "email":"test@test.com", "password":"123"}

有没有一种高效的方法可以只获取httputil.DumpRequest()中的请求体内容?也就是只获取以下内容:

> {"fname":"aFirstName", "lname":"aLName", "email":"test@test.com", "password":"123"}

英文:

I know that you can get the body content from

ioutil.ReadAll(c.Request.Body)

But using httputil.DumpRequest

dump, err := httputil.DumpRequest(c.Request, true)

will give the body contents along with other values, the body content in the end.

> Content type: application/json IP: 127.0.0.1:36846 header token: Content length: 76 Request Method: POST Request URL: /signup Body:
POST /signup HTTP/1.1
Host: 127.0.0.1:8080
Accept: /
Accept-Encoding: gzip,deflate
Accept-Language: en-US,en;q=0.8
Connection: keep-alive
Content-Type: application/json
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.101 Safari/537.36
{"fname":"aFirstName", "lname":"aLName", "email":"test@test.com", "password":"123"}

Is there an efficient way I can get only the body content from httputil.DumpRequest()? i.e In this case only

> {"fname":"aFirstName", "lname":"aLName", "email":"test@test.com", "password":"123"}

答案1

得分: 2

你不需要使用httputil.DumpRequest来实现这个功能,它是一个用于调试的函数。

假设你想解析 JSON 数据,你可以这样做:

defer c.Request.Body.Close()
var data yourDataType
if err := json.NewDecoder(c.Request.Body).Decode(&data); err != nil {
    // 处理错误
}
// 处理数据
英文:

You don't use httputil.DumpRequest for that, that's a debug function.

Assuming you want to parse json you can do something like this:

defer c.Request.Body.Close()
var data yourDataType
if err := json.NewDecoder(c.Request.Body).Decode(&data); err != nil {
    // handle error
}
// handle data

huangapple
  • 本文由 发表于 2015年8月16日 19:40:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/32034673.html
匿名

发表评论

匿名网友

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

确定