多次阅读阅读器 [英] Read multiple time a Reader
本文介绍了多次阅读阅读器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个使用相同http.ResponseWriter和* http.Request的http处理程序,并像这样读取请求正文:
I have two http handlers that use the same http.ResponseWriter and *http.Request and read the request body like this:
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的最佳方法)(如果可能的话)?).
Because of I need to keep these 2 methods separated, and both of them need to read the request Body, which is the best way (if it's possible) to Seek the request body (which is a ReadCloser, not a Seeker?).
推荐答案
实际上,感谢miku,我发现最好的解决方案是使用TeeReader,以这种方式更改Method1
Actually, thanks to miku, I've found out that the best solution is using a TeeReader, changing Method1 in this way
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)
}
这篇关于多次阅读阅读器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文