使用http.Post将JSON数据发布到远程服务器。

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

Posting json data to remote server with http.Post

问题

我被一个看起来非常简单的问题难住了。

我从客户端收到一个 JSON 对象,它看起来像这样:

{
    "user": "test@example.com"
}

我只需要将其作为 POST 请求传递给 API 的另一部分。到目前为止,我已经写了以下代码:

// 解码传入的 JSON
decoder := json.NewDecoder(r.Body)
var user UserInformation
err := decoder.Decode(&user)

if err != nil {
    log.Println(err)
}

jsonUser, _ := json.Marshal(user)

log.Println(string(jsonUser[:])) // 正确的输出
buffer := bytes.NewBuffer(jsonUser)
log.Println(string(buffer.Bytes()[:])) // 也是正确的

resp, err := http.Post("http://example.com/api/has_publisher", "application/json", buffer)
if err != nil {
    log.Println(err)
}

由于我无法在实际系统上测试这个程序,我使用 Wireshark 验证了生成的 POST 请求,结果发现内容丢失,Content-Length 为 0。由于某种原因,http.Post 不会从缓冲区中读取数据。

我在这里漏掉了什么吗?如果有人能指点我正确的方向,我将非常感激。

谢谢!

英文:

I am stumped on what seems like a very simple problem.

I am receiving a json object from a client. It looks like this:

{
    "user": "test@example.com"
}

I need to simply pass this on to another part of the api as a POST request. This is what i've got until now:

//Decode incomming json
decoder := json.NewDecoder(r.Body)
var user UserInformation
err := decoder.Decode(&user)

if err != nil {
	log.Println(err)
}

jsonUser, _ := json.Marshal(user)

log.Println(string(jsonUser[:])) //Correct output
buffer := bytes.NewBuffer(jsonUser)
log.Println(string(buffer.Bytes()[:])) //Also correct


resp, err := http.Post("http://example.com/api/has_publisher", "application/json", buffer)
if err != nil {
	log.Println(err)
}

As I cannot test this program on a live system, I verified the resulting post request with wireshark only to find that the content is missing along with Content-Length being 0. For some reason, http.Post doesn't read from the buffer.

Am i missing something here? I would greatly appreciate if someone could point me in the right direction.

Thanks!

答案1

得分: 2

不应该是根本原因,而是替换

buffer := bytes.NewBuffer(jsonUser)

buffer := bytes.NewReader(jsonUser)

更有可能是你的测试设置是根本原因。我猜你指向了一个不存在的端点。这会导致在实际的HTTP POST发送之前失败(TCP SYN失败)。

检查一下是否可以使用mockable.io作为替代来模拟你的后端。

英文:

Shouldn`t be the root cause but replace

buffer := bytes.NewBuffer(jsonUser)

with

buffer := bytes.NewReader(jsonUser)

It is more likely that your test setup is the root cause. I assume you are pointing to a non-existing endpoint. This would result in a failure (TCP SYN fails) before the actual HTTP POST is send.

Check if you can use mockable.io as an alternative to mock your backend.

huangapple
  • 本文由 发表于 2014年4月15日 17:03:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/23079087.html
匿名

发表评论

匿名网友

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

确定