英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论