[go] GIN parameter repeated binding error EOF problem

1 Problem description

In the Gin framework, when the ShouldBind() or ShouldBindJSON() method is called multiple times, the data stream of the request body will be read multiple times, resulting in an "EOF" error.

For example, binding parameters at the api layer and customizing middleware for reading parameters or binding parameters will cause repeated calls.

[ERROR] 2023/08/07 14:36:48 {“user_id”:“975674f531784289bfba3ee011ec0af0”,“trace_id”:“ae6331c69b5d474a8980c6f6ef8b86e2”,“error”:“EOF”,“position”:[{“FileName”:“D:/nscp_code/nscp/api/v1/organization.go”,“FuncName”:“nscp/api/v1.(*origanizationApi).FindByCompanyIds”,“Line”:63}]}

2 Solution: Replace with ShouldBindBodyWith

// 原本
c.ShouldBindJSON
c.ShouldBind

 // 替换为
c.ShouldBindBodyWith(&req,binding.JSON) 

At this time, the body will be cached in the context, and there will be no problem with repeated binding.

Guess you like

Origin blog.csdn.net/qq_45859826/article/details/132149430