1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Using Rack Middleware


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

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

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

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.

  1. About.com
  2. Technology
  3. Ruby
  4. Networking
  5. Rack
  6. Write Your Own Middleware

©2014 About.com. All rights reserved.