shelf icon indicating copy to clipboard operation
shelf copied to clipboard

Simplify how to remove a header

Open jxstxn1 opened this issue 2 years ago • 2 comments

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 the ifAbsent 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,
        },
      );
    };
  };
}

jxstxn1 avatar Sep 23 '22 19:09 jxstxn1

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!

kevmoo avatar Sep 23 '22 19:09 kevmoo

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 😅

jxstxn1 avatar Sep 23 '22 19:09 jxstxn1