Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use aliases for response type references #1527

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

Crystalix007
Copy link

Uses type aliases for response schema definitions.

While using a schema like:

paths:
  /example:
    get:
      responses:
        200:
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/OneOrAnother"

components:
  schemas:
    One:
      type: object

    Another:
      type: object

    OneOrAnother:
      oneOf:
        - $ref: "#/components/schemas/One"
        - $ref: "#/components/schemas/Another"

I noticed that this generated "strict" server code that looked like:

type OneOrAnother struct {
	union json.RawMessage
}

// ...

type GetExampleResponseObject interface {
	VisitGetExampleResponse(w http.ResponseWriter) error
}

type GetExampleResponseObject OneOrAnother

// ...

func (t OneOrAnother) MarshalJSON() ([]byte, error) {
	b, err := t.union.MarshalJSON()
	return b, err
}

func (t *OneOrAnother) UnmarshalJSON(b []byte) error {
	err := t.union.UnmarshalJSON(b)
	return err
}

However this doesn't actually work when doing the serialisation, because the type definition hides the definition of MarshalJSON(). Since the union field is private, this means the response that is actually serialised is {} every time.

Instead, we should just inherit that response from the referenced type definition. I.e. with type GetExampleResponseObject = OneOrAnother, the underlying MarshalJSON implementation will be picked up instead, and we can serialise the underlying union.

Includes the reftype in generated Go types. This is required to
correctly generate the response schemas as aliases.

We want these to be defined as aliases, so that we can use the
underlying JSON marshalling and unmarshalling logic.
Regenerates the examples with the new alias logic.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant