Skip to content

httpx.Parse fails to unmarshal interface{} field with mixed string/number values #5721

Description

@shinxiang

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

  1. 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
}
  1. 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
    }
}
  1. 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
    }
  ]
}
  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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions