我是Go的新手,但到目前为止,我非常喜欢它。
我有一个我不知道的问题。我正在将API从Node迁移到Go,并且有此日志必须捕获POST 原样并将其保存到jsonb
Postgresql数据库的type列中。
这意味着我不能使用struct
或预定的任何东西。
POST是使用原始身体制作的,Content-Type: application/json
如下所示:
{
"debug": false,
"order_id_gea": 326064,
"increment_id_gea": 200436102,
"date": "2017-05-18T01:44:44+00:00",
"total_amount": 10000.00,
"currency": "MXN",
"payment_method": "Referencia bancaria",
"reference": "857374",
"buyer": {
"buyer_id_gea": 1234,
"full_name": "Juan Perez Martinez",
"email": "[email protected]",
"phone": "5512341234"
},
"products": [
{
"sku":"PEP16114",
"price": 10000.00,
"currency": "MXN",
"student": {
"school_id_gea": 172,
"grade_id_gea": 119,
"level_id_gea": 36,
"name": "Benancio",
"last_name": "Perez",
"second_last_name": "Garcia",
"email": "[email protected]"
}
}
]
}
在Node + Hapi上非常简单:
const payload = request.payload
然后我可以从访问JSON payload
。
我正在将Go与Echo一起使用,所以context
可以在其中找到一个包装器Request() *http.Request
。
我已经尝试了以下方法,但是每次结果为空或因为为空而出错:
var v interface{}
err := json.NewDecoder(context.Request().Body).Decode(&v)
if err != nil {
return result, err
}
fmt.Println(v)
结果:EOF
-
m := echo.Map{}
if err := context.Bind(&m); err != nil {
return result, err
}
fmt.Println(m)
结果代码400,消息EOF
-
body, error := ioutil.ReadAll(context.Request().Body)
if error != nil {
return result, error
}
fmt.Println(body)
结果[]
-
我缺少什么和/或做错了什么?谢谢!
TIL http.Response.Body
是一个缓冲区,这意味着一旦读取它,就不能再次读取它。
就像水流一样,您可以看到它并在流过时对其进行测量,但是一旦流失,它就消失了。
但是,知道这一点,有一种解决方法,您需要“捕获”主体并将其还原:
// Read the Body content
var bodyBytes []byte
if context.Request().Body != nil {
bodyBytes, _ = ioutil.ReadAll(context.Request().Body)
}
// Restore the io.ReadCloser to its original state
context.Request().Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
// Continue to use the Body, like Binding it to a struct:
order := new(models.GeaOrder)
error := context.Bind(order)
现在,您可以在context.Request().Body
其他地方使用。
资料来源:
http://grokbase.com/t/gg/golang-nuts/12adq8a2ys/go-nuts-re-reading-http-response-body-or-any-reader
https://medium.com/@xoen/golang-read-from-an-io-readwriter-without-loosing-its-content-2c6911805361
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句