Created
September 27, 2016 08:22
-
-
Save elct9620/1707ff33160912a44ecd52400c13baa8 to your computer and use it in GitHub Desktop.
RxRuby - Simple HTTP Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# A sample Gemfile | |
source "https://rubygems.org" | |
gem "rx" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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