CWhat does CopyRequestBody mean?

In the Beego web configuration, there is a very confusing parameter called CopyRequestBody. It is in the structure web.Config.

This parameter was introduced for purpose: Beego reads the HTTP request body data and performs some processing. Also, after Beego reads it, the user can read it again.

There are two examples.

The first example with CopyRequestBody = true

  1. func main() {
  2. web.BConfig.CopyRequestBody = true
  3. web.CtrlPost("/hello", (*MainController).ReadDataFromBody)
  4. web.Run()
  5. }
  6. type MainController struct {
  7. web.Controller
  8. }
  9. func (m *MainController) ReadDataFromBody() {
  10. u := &user{}
  11. err := m.Controller.BindJson(u)
  12. if err != nil {
  13. logs.Error("could not bind json data: %v", err)
  14. }
  15. err = m.JsonResp(u)
  16. if err != nil {
  17. logs.Error("could not write json resp: %v", err)
  18. }
  19. }

When we access localhost:8080 and pass in the parameters, we can get the response: CopyRequestBody=true

If we set CopyRequestBody to false:

  1. func main() {
  2. web.BConfig.CopyRequestBody = false
  3. web.CtrlPost("/hello", (*MainController).ReadDataFromBody)
  4. web.Run()
  5. }
  6. type MainController struct {
  7. web.Controller
  8. }
  9. func (m *MainController) ReadDataFromBody() {
  10. u := &user{}
  11. err := m.Controller.BindJson(u)
  12. if err != nil {
  13. logs.Error("could not bind json data: %v", err)
  14. }
  15. err = m.JsonResp(u)
  16. if err != nil {
  17. logs.Error("could not write json resp: %v", err)
  18. }
  19. }

Then we will find that we cannot read the data from inside the request body: CopyRequestBody=false

So, be aware that you should set CopyRequestBody to true if you intend to rely on Beego to process the request.

CopyRequestBody should be considered a bit cumbersome by today’s eyes. But the advantage of it is that you can read the data from Beego multiple times. After all, the Body field inside http.Request can only be read once.

In that sense, it’s worth keeping for now. But we are considering to set its default value to true instead of false in the future.