防止golang的http.NewRequest在POST请求的正文中添加大括号。

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

Prevent golang http.NewRequest from adding braces to POST body

问题

这可能相当简单,但我无法理解为什么在使用Go进行HTTP请求时,请求的主体会被额外的一对大括号包裹起来:

package main

import (
	"bytes"
	"fmt"
	"net/http"
)

func main() {
	jsonStr := []byte(`{"some":"test","json":"data"}`)
	req, _ := http.NewRequest("POST", "http://test.com", bytes.NewBuffer(jsonStr))
	fmt.Print(req.Body)
}

结果如下:

{{"some":"test","json":"data"}}

在我的实际代码中,我使用json.Marshal和一个结构体来生成字节缓冲区,但结果相同。结果是API拒绝了请求(如预期)。

如何防止添加额外的大括号呢?

英文:

This must be fairly simple, but I can't work out why, when making an HTTP request with go, the body of the request gets wrapped in an additional set of braces:

package main

import (
	"bytes"
	"fmt"
	"net/http"
)

func main() {
	jsonStr := []byte(`{"some":"test","json":"data"}`)
	req, _ := http.NewRequest("POST", "http://test.com", bytes.NewBuffer(jsonStr))
	fmt.Print(req.Body)
}

This results in:

{{"some":"test","json":"data"}}

In my actual code I'm using the json.Marshal and a struct to generate the byte buffer, but getting the same result. The result is the API rejecting the request (as expected).

How do I prevent the extra braces being added?

答案1

得分: 7

打印出来的表示形式与读取器的内容不同。http.NewRequest函数不会在POST请求的正文中添加大括号。

具体情况如下:

正文是一个ioutil.nopCloser结构体,其中的Reader字段设置为*bytes.Buffer

fmt.Print函数将ioutil.nopCloser结构体打印为{ + 字段 + }的形式。这就是打印输出中额外的一对大括号。fmt.Print函数通过调用*bytes.Buffer.String方法打印Reader字段。String方法将内容作为字符串返回。

正文是通过读取而不是打印来发送的。

英文:

The printed representation of the body is not the same as the contents of the reader. The http.NewRequest function does not add braces to POST body.

Here's what's going on:

The body is a ioutil.nopCloser with the Reader field set to the *bytes.Buffer.

The fmt.Print function prints the ioutil.nopCloser struct as { + fields + }. This is the extra set of braces in the printed output. The fmt.Print function prints the Reader field by calling the *bytes.Buffer.String method. The String method returns the contents as a string.

The body is sent by reading it, not by printing it.

huangapple
  • 本文由 发表于 2017年7月17日 06:10:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/45133721.html
匿名

发表评论

匿名网友

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

确定