Skip to content

Simplify how to remove a header #298

Open
@jxstxn1

Description

@jxstxn1

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions