Skip to content

abstract struct Athena::Framework::Response::Writer
inherits Struct #

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

By default the content is written directly to the requests' response IO via ATH::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 < ATH::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{
      ATH::Events::Response => -256, # Listen on the Response event with a very low priority
    }
  end

  def call(event : ATH::Events::Response, dispatcher : AED::EventDispatcherInterface) : Nil
    # If the request supports gzip encoding
    if event.request.headers.includes_word?("accept-encoding", "gzip")
      # Change the `ATH::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 < ATH::Controller
  @[ATHA::Get("/users")]
  def users : Array(User)
    User.all
  end
end

ATH.run

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

Direct known subclasses

Athena::Framework::Response::DirectWriter

Constructors#

.new #

View source

Methods#

#initialize #

View source

abstract #write(output : IO, & : IO -> Nil) : Nil #

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

View source