我正在服务器端用 Golang 编写一个 http 拦截器。我可以从 r.Body
读取 http 请求正文。现在如果我想修改body内容,如何在控制传递给下一个拦截器之前修改请求体?
func(w http.ResponseWriter, r *http.Request) {
// Now I want to modify the request body, and
// handle(w, r)
}
最佳答案
正文 io.ReadCloser
似乎唯一的方法是用适合 io.ReadCloser
的对象替换 Body
界面。为此,您需要使用返回 io.Reader
对象和 ioutil.NopCloser
的任何函数构造一个 Body
对象。将 io.Reader
对象转换为 io.ReadCloser
。
bytes.NewBufferString
NewBufferString creates and initializes a new Buffer using string s as its initial contents. It is intended to prepare a buffer to read an existing string.
strings.NewReader
(在下面的示例中使用)
NewReader returns a new Reader reading from s. It is similar to bytes.NewBufferString but more efficient and read-only.
ioutil.NopCloser
NopCloser returns a ReadCloser with a no-op Close method wrapping the provided Reader r.
new_body_content := "New content."
r.Body = ioutil.NopCloser(strings.NewReader(new_body_content))
相关属性
但为了清晰且不混淆应用程序的其他部分,您需要更改与 Body
内容相关的 Request
属性。大多数时候它只是ContentLength
:
r.ContentLength = int64(len(new_body_content))
在极少数情况下,当您的新内容使用与原始 Body
不同的编码时,它可能是 TransferEncoding
。
关于http - Golang重写http请求体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33606330/