Search code examples
httpgomiddleware

How to reuse request body of *http.Request between HTTP middleware handlers?


I use go-chi as HTTP-router, and I want to reuse one method inside another

func Registration(w http.ResponseWriter, r *http.Request) {
    b, err := ioutil.ReadAll(r.Body) // if you delete this line, the user will be created   
    // ...other code

    // if all good then create new user
    user.Create(w, r)
}

...

func Create(w http.ResponseWriter, r *http.Request) {
  b, err := ioutil.ReadAll(r.Body)  
  // ...other code

  // ... there I get the problem with parse JSON from &b
}

user.Create return error "unexpected end of JSON input"

Actually, after I executed ioutil.ReadAll
user.Create ceased to parse JSON,
in r.Body there was an empty array[]how can I fix this problem?


Solution

  • In the end, I was able to recover data in this way:

    r.Body = ioutil.NopCloser(bytes.NewBuffer(b))