abstract struct Athena::Routing::Response::Writer

Overview

Determines how the content of an ART::Response will be written to the requests' response IO.

By default the content is written directly to the requests' response IO via ART::Response::DirectWriter. However, custom writers can be implemented to customize that behavior. The most common use case would be for compression.

Writers can also be defined as services and injected into a listener if they require additional external dependencies.

Example

require "athena"
require "compress/gzip"

# Define a custom writer to gzip the response
struct GzipWriter < ART::Response::Writer
  def write(output : IO, & : IO -> Nil) : Nil
    Compress::Gzip::Writer.open(output) do |gzip_io|
      yield gzip_io
    end
  end
end

# Define a new event listener to handle applying this writer
@[ADI::Register]
struct CompressionListener
  include AED::EventListenerInterface

  def self.subscribed_events : AED::SubscribedEvents
    AED::SubscribedEvents{
      ART::Events::Response => -256, # Listen on the Response event with a very low priority
    }
  end

  def call(event : ART::Events::Response, dispatcher : AED::EventDispatcherInterface) : Nil
    # If the request supports gzip encoding
    if event.request.headers.includes_word?("accept-encoding", "gzip")
      # Change the `ART::Response` object's writer to be our `GzipWriter`
      event.response.writer = GzipWriter.new

      # Set the encoding of the response to gzip
      event.response.headers["content-encoding"] = "gzip"
    end
  end
end

class ExampleController < ART::Controller
  @[ARTA::Get("/users")]
  def users : Array(User)
    User.all
  end
end

ART.run

# GET /users # => [{"id":1,...},...] (gzipped)

Direct Known Subclasses

Defined in:

response.cr

Constructors

Instance Method Summary

Constructor Detail

def self.new #

[View source]

Instance Method Detail

def initialize #

[View source]
abstract def write(output : IO, & : IO -> Nil) : Nil #

Accepts an output IO that the content of the response should be written to.


[View source]