create a http server with a get route in ruby

main.rb
require 'socket'

# Create a new TCPServer object to listen on port 8080
server = TCPServer.new('localhost', 8080)

# Loop indefinitely to handle incoming connections
loop do
  # Wait for a client to connect, then accept the connection and get the client socket
  client = server.accept
  
  # Read the HTTP request from the client socket
  request_line = client.gets
  
  # Print the request line to console
  puts request_line
  
  # Close the client socket
  client.close
end
479 chars
20 lines

This code creates a TCP server that listens on port 8080 on localhost. When a client connects to the server, the server accepts the connection, reads the HTTP request sent by the client, prints the request line to console and then closes the client socket.

To implement a specific route such as a GET request for the /hello path, you can modify the code as follows:

main.rb
require 'socket'

# Create a new TCPServer object to listen on port 8080
server = TCPServer.new('localhost', 8080)

# Loop indefinitely to handle incoming connections
loop do
  # Wait for a client to connect, then accept the connection and get the client socket
  client = server.accept
  
  # Read the HTTP request from the client socket
  request_line = client.gets
  
  # Parse the request line to get the HTTP method and path
  http_method, path, http_version = request_line.split(' ')
  
  # Check if the method is GET and the path is /hello
  if http_method == 'GET' && path == '/hello'
    # Send a successful HTTP response to the client
    client.puts "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nHello, World!"
  else
    # Send a not found HTTP response to the client
    client.puts "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\n\r\n404 Not Found"
  end
  
  # Close the client socket
  client.close
end
932 chars
29 lines

This code checks the HTTP method and path from the request line, sends a successful HTTP response with "Hello, World!" as the response body when the request is a GET request for the /hello path, and sends a not found HTTP response with a "404 Not Found" message when the request is for a different path or HTTP method.

related categories

gistlibby LogSnag