Reputation: 2068
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
}
}
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?).
Upvotes: 3
Views: 3975
Reputation: 2068
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)
}
Upvotes: 5