dqlxtv1452 2015-11-09 09:46
浏览 306

Golang重写http请求正文

I'm writing an http interceptor in Golang on the server side. I can read the http request body from r.Body. Now If I want to modify the body content, how can I modify the request body before the control is passed to the next interceptor?

func(w http.ResponseWriter, r *http.Request) {
    // Now I want to modify the request body, and 
    // handle(w, r)
}
  • 写回答

1条回答 默认 最新

  • 普通网友 2017-01-08 11:54
    关注

    Body io.ReadCloser

    It seems like the only way is to substitute a Body with an object appropriate to io.ReadCloser interface. For this purpose you need to construct a Body object using any function which returns io.Reader object and ioutil.NopCloser to turn the io.Reader object to 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 (used in an example below)

    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))
    

    Related attributes

    But to be clear and not to confuse other parts of the application you need to change Request attributes related to Body content. Most of the time it is only ContentLength:

    r.ContentLength = int64(len(new_body_content))
    

    And in a rare case, when your new content uses different encodings from original Body, it could be TransferEncoding.

    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决