Simple Status Ticker for API Endpoints

When you are deploying code left-and-right, even in a test-driven development cycle, sometimes you still want the piece of mind that your website is responding. In my case, this is specific to API endpoints and different API environments we run our products on.

Status Ticker

This script allows you to leave a mini terminal window on your screen that will refresh the status of a website at an interval of your choice. I use two gems, the first is to make the text colors pretty, and the second is for making the HTTP calls- install them like so:

> gem install httparty
> gem install terminal-display-colors

Below is the code, which can also be found on this Github gist.

require 'HTTParty'
require 'terminal-display-colors'
require 'json'

# set your endpoints!
endpoints = {
  "Google" => "http://google.com",
  "Twitter" => "http://twitter.com"
}
# seconds to sleep between pings
sleep_seconds = 10

buffer = []

def diff start, finish
  ((finish-start) * 1000.0).round(2)
end

def print_flush str
  print str
  $stdout.flush
end

while(true)
  # clear terminal
  buffer << "\e[H\e[2J"
  response_times = []
  # loop endpoints
  endpoints.each do |name, url|
    begin
      t1 = Time.now
      response = HTTParty.get url
      t2 = Time.now
      if response.code == 200
        response_times << diff(t1,t2)
        buffer << "#{name.upcase} : " + response.message.green + " (#{response_times.last}ms)".yellow
      else
        buffer << "#{name.upcase} : " + response.message.red
      end
    rescue => e
      buffer << "#{name.upcase} : " + 'Connection Error'.red 
    end
  end

  buffer << "\n"
  # display avg and max response times
  unless response_times.empty?
    buffer << "avg : #{(response_times.inject{ |sum, el| sum + el }.to_f / response_times.size).round(2)}ms".cyan
    buffer << "max : #{response_times.max}ms".cyan
  else
    buffer << 'No response times.'.cyan
  end
  # send buffered text to terminal
  puts buffer.join("\n")
  buffer.clear

  # sleep
  sleep_seconds.times
    sleep 1
    print_flush '.'
  end
end

To use the ticker, take the code and put it into a file named `status.rb` and run the following in terminal from the directory the file is located:

> ruby status.rb

To exit the ticker, use control+c on your keyboard.