oapi-codegen icon indicating copy to clipboard operation
oapi-codegen copied to clipboard

Form tag is not generated on structs when using multipart/form-data

Open sonu27 opened this issue 2 years ago • 1 comments

I get request body has an error: failed to decode request body: part Fields.0.Name: undefined

But this goes away if I manually change the generated struct to have:

`Name     string `form:"name",json:"name"`

So struct should be generated with form tag by default.

Thoughts?

sonu27 avatar Sep 14 '23 12:09 sonu27

I'm not sure what the original reporter's setup was, but I noticed this when generating a (non-strict) echo server.

For example, the OpenApi schema

openapi: "3"
info:
  title: "Issue 1262 - form tags for multipart/form-data"
  version: "1"
paths:
  /attachment:
    post:
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                description:
                  type: string
                  description: Summary description of the upload.
                data:
                  type: string
                  format: binary
                  description: User-provided file.
              required:
                - data
      responses:
        204:
          description: "No content"

generates the type

// PostAttachmentMultipartBody defines parameters for PostAttachment.
type PostAttachmentMultipartBody struct {
	// Data User-provided file.
	Data openapi_types.File `json:"data"`

	// Description Summary description of the upload.
	Description *string `json:"description,omitempty"`
}

I expected to be able to ctx.Bind() a request body into a PostAttachmentMultipartBody value, where ctx is an echo.Context. Digging in to the codegen package and echo's internals, I found a few obstacles:

  1. It looks like echo's default binder doesn't consider openapi_types.File a valid destination for a multipart file value; it uses an explicit allowlist of stdlib types.
  2. Echo only considers fields tagged with form for binding, but oapi-codegen doesn't emit these.
  3. Binding to form tags marked as omitempty is unsupported (or considered invalid?) by echo, per https://github.com/labstack/echo/issues/2612 . Not sure what the rest of the ecosystem does here though.
    • Digging in: inputFieldName here is e.g. description,omitempty rather than just description.

DMRobertson avatar May 10 '25 01:05 DMRobertson