Skip to content

Instantly share code, notes, and snippets.

@elct9620
Created September 27, 2016 08:22
Show Gist options
  • Save elct9620/1707ff33160912a44ecd52400c13baa8 to your computer and use it in GitHub Desktop.
Save elct9620/1707ff33160912a44ecd52400c13baa8 to your computer and use it in GitHub Desktop.
RxRuby - Simple HTTP Server
# frozen_string_literal: true
# A sample Gemfile
source "https://rubygems.org"
gem "rx"
# Load Ruby Gems
require 'rubygems'
require 'bundler'
Bundler.require
server = TCPServer.new('0.0.0.0', 8080)
rx_request = Rx::Subject.new
PATH_RULE = /^GET\s+(?<path>[^\s]+).+?/
events = rx_request.as_observable.map do |request, response|
matches = PATH_RULE.match(request)
[matches[:path], response]
end
events.subscribe do |path, response|
msg = "Hi, you try to get #{path}"
response.print [
"HTTP/1.1 200 OK",
"Content-Type: text/plain",
"Content-Length: #{msg.bytesize}",
"Connection: close",
"",
msg
].join("\r\n")
end
loop do
socket = server.accept
request = socket.gets
rx_request.on_next [request, socket]
socket.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment