How to read request body twice in Golang middleware?

后端 未结 1 1830
抹茶落季
抹茶落季 2021-02-07 06:08

In a middleware, I want to read request body to perform some checks. Then, the request is passed to the next middleware where the body will be read again. Here\'s what I do:

相关标签:
1条回答
  • 2021-02-07 07:08

    Will it break since the previous req.Body.Close implementation did some connection handling?

    No.

    But your code is buggy: You should close the req.Body once you are done reading all of it. Then you construct a new ReadCloser as you did and hand this to the next middleware (which itself or stuff further down is responsible for closing is.)

    bodyBytes, _ := ioutil.ReadAll(req.Body)
    req.Body.Close()  //  must close
    req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
    
    0 讨论(0)
提交回复
热议问题