Limit response size with go-swagger openAPI

Viewed 818

I'm using go-swagger openAPI for generating a REST client.

Now I would like to limit the response size to a maximum of e.g. 1MB. In Go this would mean using a LimitReader when consuming the body of the response.

Is there a way to limit the response size with go-swagger openAPI as well?

1 Answers

You'll want to implement a custom runtime.Consumer, then use it when implementing your client.

Your generated client code will have exported variadic functions that allow for an arbitrary number of client options to be passed in. These client options will be a Go type (ClientOption) that is a function that accepts a *runtime.ClientOperation.

Create a ClientOption function that will assign its argument's Reader field to a custom runtime.ClientResponseReader interface implementation. This custom implementation should wrap the old one, but use your desired consumer.

Custom runtime.Consumer

type customLimitConsumer struct {
    limit int64
}

func (c customLimitConsumer) Consume(reader io.Reader, i interface{}) error {

    // Read all the data, up to the limit.
    data, err := ioutil.ReadAll(io.LimitReader(reader, c.limit))
    if err != nil {
        return err
    }

    // TODO Unmarshal data into i.

    return nil
}

Custom runtime.ClientResponseReader wrapper.

type myClientResponseReader struct {
    consumer                runtime.Consumer
    oldClientResponseReader runtime.ClientResponseReader
}

func (m myClientResponseReader) ReadResponse(response runtime.ClientResponse, _ runtime.Consumer) (interface{}, error) {
    return m.oldClientResponseReader.ReadResponse(response, m.consumer)
}

Custom ClientOption function to pass as an argument to generated variadic function

var myClientOption api.ClientOption
myClientOption = func(operation *runtime.ClientOperation) {
    oldReader := operation.Reader
    operation.Reader = myClientResponseReader{
        consumer: customLimitConsumer{
            limit: 1000000,
        },
        oldClientResponseReader: oldReader,
    }
}
Related