Skip to content

Add body method and common interface to responses in ClientWithResponses #240

@ernestas2k

Description

@ernestas2k

Description

Simplest use case - we need to check status code and in case of error - print the response body.
The generator generates:

type createObjectResponse struct {
	Body         []byte
	HTTPResponse *http.Response
	JSON201      *ObjectCreateResponse
}

// Status returns HTTPResponse.Status
func (r createObjectResponse) Status() string {
	if r.HTTPResponse != nil {
		return r.HTTPResponse.Status
	}
	return http.StatusText(0)
}

// StatusCode returns HTTPResponse.StatusCode
func (r createObjectResponse) StatusCode() int {
	if r.HTTPResponse != nil {
		return r.HTTPResponse.StatusCode
	}
	return 0
}

the HTTPResponse doesn't have body anymore, since it was consumed during parsing and populating Body and JSON201. Since every response is a different struct type - you would have to handle them case by case in every place you perform a call. There's no way we can introduce common handler methods for all responses.

  1. The idea (although I believe has some implications..) is to add a new method for each response GetBody() []byte (Body() is reserved by the field).
    This way we can now introduce our own common interface for the responses without introducing any interfaces to oapi-codegen.
type XXX interface {
	StatusCode() int
}
  1. Additionally, we could add the following snippet to client-with-responses.tmpl so the interface is available out of the box.
type Response interface {
    Status()     string
    StatusCode() int
    GetBody()    []byte
}

PS: Currently, we have overriden the client-with-responses.tmpl in our project to have both of the mentioned improvements. I am still interested in your thoughts whether you would want to put those improvements into the oapi-codegen.

I'm ready to open a PR for the improvements if needed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions