1. Computing

Using Rack Middleware

By

4 of 4

Write Your Own Middleware

Now that we know how to use middleware applications, let’s write one to get rid of that ugly Content-Type header from our HelloWorld application. What this middleware application will do is, when initialized, store a copy of the app that it’s middling for. It’ll then pass on any requests to that application, add its own headers to the response headers and return them.

#\ -p 1337

class ContentTypeHTML
  def initialize(app)
    @app = app
  end

  def call(env)
    status, headers, body = @app.call(env)
    headers.merge!( 'Content-Type' => 'text/html' )
    return [status, headers, body]
  end
end

class HelloWorld
  def call(env)
    return [200, {}, ["Hello world!"]]
  end
end

use Rack::ContentLength
use ContentTypeHTML
run HelloWorld.new

Now that you know how to use and write Rack middleware applications with Rackup, the possibilities are endless. You can use it as above to tack on simple headers without having to touch the application, or you can go even further and implement things like Intrusion Detection Systems. It’s a simple and very powerful feature, to say the least.

©2014 About.com. All rights reserved.