Skip to content

Add an output option for generating a default case in response parsing function #1923

Description

@MilkeeyCat

There're times when you don't want to list all of the possible responses and you only care about a few(or you don't all of the responses), but you would like to know if there was an unexpected response. Currently using this yaml file:

openapi: 3.0.3
paths:
  /test:
    post:
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Foo'
components:
  schemas:
    Foo:
      type: object
      properties:
        bar:
          type: string
      required:
        - bar

You get such a parsing function:

func ParsePostTestResponse(rsp *http.Response) (*PostTestResponse, error) {
    bodyBytes, err := io.ReadAll(rsp.Body)
    defer func() { _ = rsp.Body.Close() }()
    if err != nil {
        return nil, err
    }

    response := &PostTestResponse{
        Body:         bodyBytes,
        HTTPResponse: rsp,
    }

    switch {
    case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200:
        var dest Foo
        if err := json.Unmarshal(bodyBytes, &dest); err != nil {
            return nil, err
        }
        response.JSON200 = &dest

    }

    return response, nil
}

The new output option would make the switch look like this:

switch {
    case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200:
        var dest Foo
        if err := json.Unmarshal(bodyBytes, &dest); err != nil {
            return nil, err
        }
        response.JSON200 = &dest
    default:
        return nil, ErrUnexpectedResponse
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesthelp wantedExternal contributions would be very much appreciated!

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions