2015-11-04 57 views
1

我有一個http請求,我需要檢查的身體。但是當我這樣做時,請求失敗。我假設這與閱讀器需要重置有關,但沿着go ioutil reset ReadCloser的線搜索並沒有改變任何看起來很有希望的東西。在Go中,我如何重用ReadCloser?

c*middleware.Contextc.Req.Request是一個http.Requestc.Req.Request.Bodyio.ReadCloser

contents, _ := ioutil.ReadAll(c.Req.Request.Body) 
log.Info("Request: %s", string(contents)) 
proxy.ServeHTTP(c.RW(), c.Req.Request) 

具體來說,我得到的錯誤是http: proxy error: http: ContentLength=133 with Body length 0

回答

4

你不能重置,因爲你已經已經從中讀取並且流中沒有任何內容。

你可以做的就是把你已經有了緩衝的字節數,並用新的io.ReadCloser

contents, _ := ioutil.ReadAll(c.Req.Request.Body) 
log.Info("Request: %s", string(contents)) 
c.Req.Request.Body = ioutil.NopCloser(bytes.NewReader(contents)) 
proxy.ServeHTTP(c.RW(), c.Req.Request) 
更換閥體