Skip to content

Instantly share code, notes, and snippets.

@litch
Created July 1, 2016 19:48
Show Gist options
  • Save litch/cb8ba86fd369c306059b2f073d57c82e to your computer and use it in GitHub Desktop.
Save litch/cb8ba86fd369c306059b2f073d57c82e to your computer and use it in GitHub Desktop.
Health check HTTP endpoint for a ruby (micro)service
# This is used to provide a Health Check HTTP endpoint
# 1- Each project should have a particular endpoint(s), they should not overlap
# so that mulitple services running on a single node will not confuse our
# operations (this isn't docker, there are rules.)
# 2- If you pass a block to the build method, that code will be evaluated and
# merged into the check. The return type of that block should be a hash
# Usage examples:
# Health.build(2700).start!
#
# Health.build(2700) do
# {random_number: rand(100}
# end.start!
class Health
attr_reader :port_number
attr_reader :check
def self.build port_number, &block
instance = new port_number, &block
end
def initialize port_number, &block
@port_number = port_number
@check = block
end
def start!
Thread.new {
require 'socket'
require 'json'
server = TCPServer.new('localhost', port_number)
@start_time = Time.now
loop do
socket = server.accept
request = socket.gets
response_hash = {uptime: Time.now - @start_time}
response_hash.merge! check.call if check
response = JSON.pretty_generate(response_hash)
socket.print "http/1.1 200 ok\r\n" +
"content-type: application/json\r\n" +
"content-length: #{response.bytesize}\r\n" +
"connection: close\r\n"
socket.print "\r\n"
socket.print response
socket.close
end
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment