http - Golang重写http请求体

标签 http go request interceptor

我正在服务器端用 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/

相关文章:

http - 使用 jQuery 附加 HTML 表单时提交按钮不起作用

go - 通过 exec.Command 使用 rsh 选项运行 rsync

javascript - 等到页面准备好加载所有社交媒体按钮

go - 打印字符串的底线被剪掉

google-app-engine - google.golang.org/appengine/datastore 与 cloud.google.com/go/datastore

java - 可以检索完整的 header 或 header 的大小吗?

javascript - 使用 Node.js 中的 API 调用清除 Cloudflare 缓存

ios - NSURLSession 在什么情况下会为其数据返回 nil?

javascript - q-io : how to read response. 使用 Promises 的主体 JSON 对象?

http - 在服务器上设置基本的 Scala 程序