Created
June 13, 2020 01:50
-
-
Save condef5/5cc11f0ff027b0f4ccc2f61294bf01b3 to your computer and use it in GitHub Desktop.
Ruby Code
This file contains 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' | |
module MyServer | |
@@routes = { | |
"/" => "Hello World!\n" | |
} | |
def response(socket, content) | |
socket.print "HTTP/1.1 200 OK\r\n" + | |
"Content-Type: text/plain\r\n" + | |
"Content-Length: #{content.bytesize}\r\n" + | |
"Connection: close\r\n" | |
socket.print "\r\n" | |
socket.print content | |
socket.close | |
end | |
def start_server | |
server = TCPServer.new('localhost', 8080) | |
loop do | |
socket = server.accept | |
request = socket.gets | |
method, path, version = request.lines[0].split | |
unless @@routes.has_key?(path) | |
response(socket, "Route not found\n") | |
next | |
end | |
content = @@routes[path] | |
response(socket, content) | |
end | |
end | |
def get(path, &block) | |
@@routes[path] = block.call + "\n" | |
end | |
end | |
include MyServer # include module's methods into current scope | |
get '/home' do | |
"Hey, welcome to jungle" | |
end | |
get '/about' do | |
"We are fsociety" | |
end | |
start_server | |
# tests this simple server with curl | |
# curl localhost:8080/about => 'We are fscociety' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment