这是indexloc提供的服务,不要输入任何密码
Skip to content

Parsing a struct in Multipart Form Data panics #897

@firu11

Description

@firu11

I've seen that parsing arbitrary types has been implemented just recently.

curl http://localhost:9999/foo \
    --form 'name=josh' \
    --form 'content=@abc.pdf'

Parses fine into:

type Input struct {
	RawBody huma.MultipartFormFiles[struct {
		Name    string        `form:"name"`
		Content huma.FormFile `form:"content"`
	}]
}

But imagine a scenario where I need to upload a file (possibly binary) to the server. And alongside this file, I want to send some additional metadata as JSON. Like this:

curl http://localhost:9999/foo \
    --form 'metadata={\"client\":\"curl\", \"user_id\":1}' \
    --form 'content=@abc.pdf'

Then, I would try to define the Input struct as follows:

type Input struct {
	RawBody huma.MultipartFormFiles[struct {
		Metadata Metadata      `form:"metadata" contentType:"application/json"`
		Content  huma.FormFile `form:"content"`
	}]
}
type Metadata struct {
	Client string `json:"client"`
	UserID int    `json:"user_id"`
}

With that, Huma even generates the right OpenAPI spec:

...
Metadata:
  additionalProperties: false
  properties:
    client:
      type: string
    user_id:
      format: int64
      type: integer
  required:
    - client
    - user_id
  type: object
...
requestBody:
  content:
    multipart/form-data:
      encoding:
        content:
          contentType: application/octet-stream
        metadata:
          contentType: text/plain
      schema:
        properties:
          content:
            contentEncoding: binary
            contentMediaType: application/octet-stream
            format: binary
            type: string
          metadata:
            $ref: "#/components/schemas/Metadata"
        type: object
...

But sadly, the parsing then fails when a request is fired.

http: panic serving [::1]:50273: unsupported param type Metadata

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions