我有两个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
}
}
因为我需要将这两个方法分开,并且它们都需要读取请求Body,这是寻求请求体(这是一个ReadCloser,而不是搜索者)的最佳方式(如果可能的话)? )。
答案 0 :(得分:2)
实际上,感谢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)
}