如何从请求的正文中获取JSON

编程入门 行业动态 更新时间:2024-10-28 10:25:20
本文介绍了如何从请求的正文中获取JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是Go的新手,但到目前为止,我非常喜欢它。

我有个问题,我找不出来。我正在将一个API从Node迁移到Go,并且存在这个日志,我必须捕获POST正文 原样 并将其保存到 jsonb 在Postgresql数据库中输入列。

这意味着我不能使用 struct 或任何预定的内容。

POST是使用body raw 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_id_gea:1234,全名:Juan Perez Martinez,电子邮件:juanperez@gmail,电话:5512341234},产品:[ {sku: PEP16114,price:10000.00,currency:MXN,学生:{school_id_gea:172, grade_id_gea:119,level_id_ gea:36,name:Benancio,last_name:Perez,second_last_name:Garcia,email: benancio@gmail} ] }

Node + Hapi非常简单:

const payload = request.payload

然后我可以从有效负载访问JSON。

我使用Go with 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 {返回结果,err } fmt.Println(m)

结果代码400,消息EOF

-

body,error:= ioutil.ReadAll(context.Request()。Body) if error!= nil {返回结果,错误} fmt。 Println(body)

结果[]

-

我错过了什么和/或做错了什么?谢谢!

解决方案

TIL http.Response.Body 是一个缓冲区,这意味着一旦它被读取,它就不能被再次读取。

它就像一股水流,你可以看到它并在它经过时测量它,但是一次它已经消失了,它已经消失了。

然而,知道这一点,有一个解决方法,你需要抓住主体并恢复它:

//读取正文内容 var bodyBytes [] byte if context.Request()。Body!= nil { bodyBytes,_ = ioutil.ReadAll(context.Request()。Body)} //将io.ReadCloser恢复到原始状态 context.Request( ).Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) //继续使用Body,如将它绑定到一个结构体: order:= new(models.GeaOrder ) error:= context.Bind(order)

现在,您可以使用 context.Request()。Body 其他地方。

S资源:

grokbase/t/gg/golang-nuts/12adq8a2ys/go-nuts-re-reading-http-response-body-or -any-reader

medium/@xoen/golang-read-from-an-io-readwriter-without-loosing-its-content-2c6911805361

I'm a newbie with Go, but so far I'm liking it very much.

I have a problem I can't figure out. I'm migrating an API from Node to Go and there is this log where I have to capture the Body of a POST AS IT IS and save it to a jsonb type column in a Postgresql database.

This means I can't use a struct or anything predetermined.

The POST is made with body raw Content-Type: application/json like so:

{ "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": "juanperez@gmail", "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": "benancio@gmail" } } ] }

On Node + Hapi is quite simple:

const payload = request.payload

and then I can access the JSON from payload.

I am using Go with Echo, so context is a wrapper where I can find Request() *http.Request.

I have tried the following, but everytime the result is empty or an error because it is empty:

var v interface{} err := json.NewDecoder(context.Request().Body).Decode(&v) if err != nil { return result, err } fmt.Println(v)

Result: EOF

--

m := echo.Map{} if err := context.Bind(&m); err != nil { return result, err } fmt.Println(m)

Result code 400, message EOF

--

body, error := ioutil.ReadAll(context.Request().Body) if error != nil { return result, error } fmt.Println(body)

Result []

--

What am I missing and/or doing wrong? Thanks!

解决方案

TIL that http.Response.Body is a buffer, which means that once it has been read, it cannot be read again.

It's like a stream of water, you can see it and measure it as it passes but once it's gone, it's gone.

However, knowing this, there is a workaround, you need to "catch" the body and restore it:

// 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)

Now, you can use context.Request().Body somewhere else.

Sources:

grokbase/t/gg/golang-nuts/12adq8a2ys/go-nuts-re-reading-http-response-body-or-any-reader

medium/@xoen/golang-read-from-an-io-readwriter-without-loosing-its-content-2c6911805361

更多推荐

如何从请求的正文中获取JSON

本文发布于:2023-10-29 07:36:00,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文中   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!