Skip to content

Instantly share code, notes, and snippets.

@mojavelinux
Last active January 8, 2019 23:02
Show Gist options
  • Save mojavelinux/a7e0cabb1b401300a4a5f7fa1ea6689c to your computer and use it in GitHub Desktop.
Save mojavelinux/a7e0cabb1b401300a4a5f7fa1ea6689c to your computer and use it in GitHub Desktop.
Running an HTTP server in a background thread in Ruby (for use in tests, for example)
# serve multiple clients at once
require 'socket'
require 'net/http'
server = TCPServer.new 4040
server_thread = Thread.start do
loop do
Thread.start server.accept do |socket|
/^GET (\S+) HTTP\/1\.1$/ =~ socket.gets.chomp
path = $1
sleep 0.5
socket.print %(HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n)
socket.print %({ "path": "#{path}" }\n)
socket.close
end
end
end
# emulate work, such as a test case
%w(/foo /bar /baz).map {|path|
Thread.start { puts Net::HTTP.get 'localhost', path, 4040 }
}.each(&:join)
# you may want to put this final part in an ensure block
server_thread.exit
server_thread.value
server.close
# serve a single client at once
require 'socket'
require 'net/http'
server = TCPServer.new 4040
server_thread = Thread.start do
while (socket = server.accept) do
/^GET (\S+) HTTP\/1\.1$/ =~ socket.gets.chomp
path = $1
sleep 0.5
socket.print %(HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n)
socket.print %({ "path": "#{path}" }\n)
socket.close
end
end
# emulate work, such as a test case
%w(/foo /bar /baz).map {|path|
Thread.start { puts Net::HTTP.get 'localhost', path, 4040 }
}.each(&:join)
# you may want to put this final part in an ensure block
server_thread.exit
server_thread.value
server.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment