Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Stuck in the Middle: Leverage the power of Rack...

Stuck in the Middle: Leverage the power of Rack::Middleware

Before a request ever hits your Rails application, it winds its way through a series of pieces of Rack middleware. Middleware sets session cookies, writes your logs, and enables the functionality in many gems such as Warden.

With Rails or any Rack app, you can easily insert your own custom middleware, allowing you to log, track, redirect, and alter the incoming request before it hits your application.

You will leave this talk confident in writing your own custom middleware, better able to troubleshoot gems that rely on middleware and with an understanding of how your Rails app functions.

Amy Unger

May 04, 2016
Tweet

More Decks by Amy Unger

Other Decks in Programming

Transcript

  1. CGI

  2. { "PATH_INFO" => "/ping.json", "QUERY_STRING" => "", "REQUEST_METHOD" => "GET",

    "REQUEST_URI" => "http://localhost:3000/ping.json", "REQUEST_PATH" => "/ping.json" ... }
  3. # Middleware::Ping def call(env) request = Rack::Request.new(env) return @app.call(env) unless

    request.path == ‘/ping’ [‘200’, {}, [“Pong!”]] end
  4. # Middleware::RequestTimeLogging def call(env) start = Time.now status, headers, response

    = @app.call(env) elapsed = Time.now - start [status, headers, response] end
  5. # Middleware::RequestTimeLogging def call(env) start = Time.now status, headers, response

    = @app.call(env) elapsed = Time.now - start [status, headers, response] end
  6. # Middleware::RequestTimeLogging def call(env) start = Time.now status, headers, response

    = @app.call(env) elapsed = Time.now - start log_response_time( elapsed ) [status, headers, response] end
  7. # Middleware::RequestTimeLogging def call(env) start = Time.now status, headers, response

    = @app.call(env) elapsed = Time.now - start request = Rack::Request.new(env) log_response_time( elapsed, request ) [status, headers, response] end
  8. # Middleware::RequestTimeLogging def log_response_time(elapsed_time, request) payload = { response_time_secs: elapsed_time,

    path: request.path } SplunkLogger.log(‘request.response_time’, payload) end
  9. Some Red Flags §  Modifying the request §  Awareness of

    business logic §  Awareness of models