Describe the bug
httpx.Parse fails to parse a request body that contains an interface{} field when the actual JSON value can be either a string or a number. The same request works perfectly with json.NewDecoder(r.Body).Decode(&req), indicating that the JSON is valid and the structure definition is correct.
To Reproduce
- Define the following API types:
type UpdateReq struct {
Id uint64 `json:"id"`
Items []DataItem `json:"datas,optional"`
}
type DataItem struct {
Value interface{} `json:"value,omitempty"` // can be string or number
ValueType int `json:"valueType"` // 0 for string, 1 for number
}
- Handler code that uses httpx.Parse:
func UpdateDataHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.UpdateReq
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
// ... business logic
}
}
- Send a POST request with the following JSON body (no query or form parameters):
{
"id": "123",
"datas": [
{
"value": "1",
"valueType": 0
},
{
"value": 2,
"valueType": 1
}
]
}
- The error returned is:
type mismatch for field "datas[0].value"
Use the following method to resolve successfully
func UpdateDataHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.UpdateReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
// ... business logic
}
}
Environments
go-zero version: v1.10.2
goctl version: v1.10.1
Go version: 1.24.0
Describe the bug
httpx.Parsefails to parse a request body that contains aninterface{}field when the actual JSON value can be either a string or a number. The same request works perfectly withjson.NewDecoder(r.Body).Decode(&req), indicating that the JSON is valid and the structure definition is correct.To Reproduce
{ "id": "123", "datas": [ { "value": "1", "valueType": 0 }, { "value": 2, "valueType": 1 } ] }Use the following method to resolve successfully
Environments
go-zero version: v1.10.2
goctl version: v1.10.1
Go version: 1.24.0