@Override
    protected HttpObject filter(HttpObject obj) {
        if (obj instanceof ResponseHeaders) {
            final ResponseHeaders headers = (ResponseHeaders) obj;

            // Skip informational headers.
            final HttpStatus status = headers.status();
            if (status.isInformational()) {
                return obj;
            }

            if (headersSent) {
                // Trailers, no modification.
                return obj;
            }

            headersSent = true;
            if (!shouldEncodeResponse(headers)) {
                return obj;
            }

            final ByteBuf buf;
            final long contentLength = headers.contentLength();
            if (contentLength > 0) {
                // A compression ratio heavily depends on the content but the compression ratio is higher than
                // 50% in common cases.
                buf = alloc.buffer(Ints.saturatedCast(contentLength) / 2);
            } else {
                buf = alloc.buffer();
            }
            encodedStream = new ByteBufOutputStream(buf);
            encodingStream = encoderFactory.newEncoder(encodedStream);

            final ResponseHeadersBuilder mutable = headers.toBuilder();
            // Always use chunked encoding when compressing.
            mutable.remove(HttpHeaderNames.CONTENT_LENGTH);
            mutable.set(HttpHeaderNames.CONTENT_ENCODING, encoderFactory.encodingHeaderValue());
            mutable.set(HttpHeaderNames.VARY, HttpHeaderNames.ACCEPT_ENCODING.toString());
            return mutable.build();
        }

        if (obj instanceof HttpHeaders) {
            // Trailers.
            return obj;
        }

        if (encodingStream == null) {
            // Encoding was disabled for this response.
            return obj;
        }

        final HttpData data = (HttpData) obj;
        assert encodedStream != null;
        try {
            encodingStream.write(data.array());
            encodingStream.flush();
            final ByteBuf encodedBuf = encodedStream.buffer();
            final HttpData httpData = HttpData.wrap(encodedBuf.retainedSlice());
            encodedBuf.readerIndex(encodedBuf.writerIndex());
            return httpData;
        } catch (IOException e) {
            // An unreleased ByteBuf in `encodedStream` will be released by `beforeError()`
            throw new IllegalStateException(
                    "Error encoding HttpData, this should not happen with byte arrays.",
                    e);
        }
    }
A {@link FilteredStreamMessage} that applies HTTP encoding to {@link HttpObject}s as they are published.
core/src/main/java/com/linecorp/armeria/server/encoding/HttpEncodedResponse.java