【问题标题】:Read multiple time a Reader多次阅读 Reader
【发布时间】:2015-08-07 18:07:36
【问题描述】:

我有两个 http 处理程序,它们使用相同的 http.ResponseWriter 和 *http.Request 并像这样读取请求正文:

func Method1 (w http.ResponseWriter, r *http.Request){
    var postData database.User
    if err := json.NewDecoder(r.Body).Decode(&postData); err != nil {
      //return error
    }
}

func Method2 (w http.ResponseWriter, r *http.Request){
    var postData database.User
    //this read gives (of course) EOF error
    if err := json.NewDecoder(r.Body).Decode(&postData); err != nil {
      //return error
    }
}

因为我需要将这两个方法分开,并且它们都需要读取请求正文,这是寻找请求正文(这是 ReadCloser,而不是 Seeker? )。

【问题讨论】:

标签: go


【解决方案1】:

实际上,感谢 miku,我发现最好的解决方案是使用 TeeReader,以这种方式更改 Method1

func Method1 (w http.ResponseWriter, r *http.Request){
    b := bytes.NewBuffer(make([]byte, 0))
    reader := io.TeeReader(r.Body, b)

    var postData MyStruct
    if err := json.NewDecoder(reader).Decode(&postData); err != nil {
        //return an error
    }

    r.Body = ioutil.NopCloser(b)
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
  • 1970-01-01
  • 1970-01-01
  • 2011-01-27
  • 2020-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多