shelf
shelf copied to clipboard
Simplify how to remove a header
If I currently want to remove a Header in a middleware I have to do:
- Get the current header Map
- Remove the header out there
- Change the response and explicitly set the header in it to null
or:
- Get the current header Map
- call the
update
function, and set theifAbsent
Option
I think it should be enough to just update the headers with the .removeWhere
function and not also need to set it null
in the response.
Example for first way of removing the header:
Middleware xPoweredBy() {
return (innerHandler) {
return (request) async {
final response = await innerHandler(request);
// We need to remove the header in the updated list...
final headers = {...response.headersAll}..remove('Content-Type');
return response.change(
headers: {
// ... and set it here to null, to actually remove it.
'Content-Type': null,
...headers,
},
);
};
};
}
Example second way:
Middleware xPoweredBy() {
return (innerHandler) {
return (request) async {
final response = await innerHandler(request);
final headers = {...response.headersAll}..update(
'X-Powered-By',
(_) => [],
ifAbsent: () => [],
);
return response.change(
headers: {
...headers,
},
);
};
};
}
The x-powered-by
bit was fixed here: https://github.com/dart-lang/shelf/commit/ca731ab09eba26d6e301fbc882a65621cb3cfed4 – and published!
The other bits are interesting. Something to investigate!
Keep in mind, we want the Request and Response bodies to be immutable – it makes many of the operations in the ecosystem easier to model. But your point is taken!
Thanks for the response and the acknowledgment :)
The x-powered-by
header was just an example, it will apply to any other header too.
Edit: Added the middleware to the example and made a request in Postman, even this Middleware isn't capable of removing the header 😅