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

Maximum allowed response length #617

Closed
Tracked by #1684
jiripospisil opened this issue Sep 17, 2018 · 5 comments
Closed
Tracked by #1684

Maximum allowed response length #617

jiripospisil opened this issue Sep 17, 2018 · 5 comments
Labels
documentation The issue will improve the docs ✭ help wanted ✭

Comments

@jiripospisil
Copy link

It would be great if it was possible to set the maximum allowed response length. If the response was larger than that, it would report an error. It should not rely on the response's Content-Length.

Looking at the available API, it could be done manually by consuming the response as stream and counting but exposing it as an option would be more user friendly.

const response = await got(url, {
  maxResponseLength: 123, // bytes
});
@szmarczak
Copy link
Collaborator

@benjie Good spot. Also it's not compatible with streams, since they use stream.destroy. Although we can make stream.cancel an alias to stream.destroy.

@benjie
Copy link

benjie commented Nov 12, 2020

That seems wise; or update the doc. Thanks for the heads up 🙏

@szmarczak szmarczak reopened this Nov 12, 2020
@szmarczak szmarczak added documentation The issue will improve the docs ✭ help wanted ✭ labels Nov 12, 2020
@szmarczak szmarczak mentioned this issue Apr 11, 2021
13 tasks
@szmarczak
Copy link
Collaborator

Updated:

// Limiting download & upload size
// This can prevent crashing due to insufficient memory
const limitDownloadUpload = got.extend({
handlers: [
(options, next) => {
const {downloadLimit, uploadLimit} = options.context;
let promiseOrStream = next(options);
// A destroy function that supports both promises and streams
const destroy = message => {
if (options.isStream) {
promiseOrStream.destroy(new Error(message));
return;
}
promiseOrStream.cancel(message);
};
if (typeof downloadLimit === 'number') {
promiseOrStream.on('downloadProgress', progress => {
if (progress.transferred > downloadLimit && progress.percent !== 1) {
destroy(`Exceeded the download limit of ${downloadLimit} bytes`);
}
});
}
if (typeof uploadLimit === 'number') {
promiseOrStream.on('uploadProgress', progress => {
if (progress.transferred > uploadLimit && progress.percent !== 1) {
destroy(`Exceeded the upload limit of ${uploadLimit} bytes`);
}
});
}
return promiseOrStream;
}
]
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation The issue will improve the docs ✭ help wanted ✭
Projects
None yet
Development

No branches or pull requests

3 participants