Created
December 5, 2012 07:31
-
-
Save MitinPavel/4213424 to your computer and use it in GitHub Desktop.
A dead simple API web server contains three endpoints: fibonacci numbers, Google's home page sha1, a simple store.
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
require 'socket' | |
require 'net/https' | |
require 'uri' | |
require 'digest/sha1' | |
def fibonacci(n) | |
n < 2 ? n : fibonacci(n-1) + fibonacci(n-2) | |
end | |
def google_body | |
uri = URI.parse 'https://www.google.com.ua/' | |
http = Net::HTTP.new uri.host, uri.port | |
http.use_ssl = true | |
http.verify_mode = OpenSSL::SSL::VERIFY_NONE | |
response = http.request Net::HTTP::Get.new(uri.request_uri) | |
Digest::SHA1.hexdigest response.body | |
end | |
def set_value(value) | |
`echo "#{value}" > store` | |
end | |
def get_value | |
`cat store`.chop | |
end | |
def value_from_request(socket) | |
while (line = socket.gets) | |
if line =~ /^Content-Length: (\d+)/ | |
content_length = $1.to_i | |
elsif line == "\r\n" | |
break | |
end | |
end | |
socket.read(content_length).match(/^value=(.+)/)[1] | |
end | |
server = TCPServer.new 2000 | |
loop do | |
socket = server.accept | |
case socket.gets | |
when /^GET \/fib\/(\d+)/ then socket.puts "{\"response\": #{fibonacci($1.to_i)}}" | |
when /^GET \/google-body/ then socket.puts "{\"response\": #{google_body}}" | |
when /^GET \/google-body/ then socket.puts "{\"response\": #{google_body}}" | |
when /^GET \/store/ then socket.puts "{\"response\": \"#{get_value}\"}" | |
when /^POST \/store/ then set_value(value_from_request(socket)) and socket.puts("{\"response\": \"ok\"}") | |
else socket.puts "{\"error\": \"Unknown request\"}" | |
end | |
socket.close | |
end |
dmitriy-kiriyenko
commented
Dec 5, 2012
here I loose testing gets for nil. Not sure if it's important.
Assuming it is a POST request with "value=blah" payload, you can safely skip the check.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment