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

1.12.0+ generated struct style for arrays is broken

Open Southclaws opened this issue 3 years ago • 4 comments

Due to how Go's JSON encoding works with composed structs, this breaks 1.12.0+

For an example of how Go's struct composition works with JSON encoding, see this playground link:

https://go.dev/play/p/pofURCwIv3i

Basically this makes 1.12.0+ unusable since the API response does not match the schema any more:

image

Southclaws avatar Nov 11 '22 17:11 Southclaws

Thanks for raising this! Would you mind sharing a minimal OpenAPI spec to run this against, so we can confirm expected behaviour before/after the v1.12.0 release?

jamietanna avatar Nov 12 '22 20:11 jamietanna

Sure thing, here's a minimal spec:

openapi: 3.0.0

servers: [{ url: localhost:8000 }]

paths:
  /test:
    post:
      operationId: TestEndpoint
      security: []
      responses:
        "200": { $ref: "#/components/responses/TestResponse" }

components:
  responses:
    TestResponse:
      description: OK
      content:
        application/json:
          schema: { $ref: "#/components/schemas/TestResponseSchema" }

  schemas:
    TestResponseSchema:
      type: array
      items: { $ref: "#/components/schemas/TestResponseItem" }

    TestResponseItem:
      type: object
      properties:
        xyz:
          type: string

Which generates the code in here: https://go.dev/play/p/Dea18vQkqkz (which doesn't run in the playground as it's too big...)

So I just took the structs and wrote a quick JSON marshal for that: https://go.dev/play/p/e_dVsdSGLTk output:

{"TestResponseJSONResponse":[{"xyz":"string"}]}

Southclaws avatar Dec 21 '22 10:12 Southclaws

Upgrade another project, this time to v1.12.4, and just ran into this issue again:

https://github.com/Southclaws/storyden/blob/main/api/openapi.yaml#L343-L363

https://github.com/Southclaws/storyden/blob/main/api/openapi.yaml#L612-L619

https://github.com/Southclaws/storyden/blob/main/internal/openapi/generated.go#L4226

Edit: Apologies I didn't link an exact commit here so the above links are a bit useless!

Southclaws avatar Jan 14 '23 13:01 Southclaws