return a text response from a http server in ruby

To return a text response from a HTTP server in Ruby, you can use the following code:

main.rb
require 'socket'

server = TCPServer.new(8080)

loop do
  client = server.accept
  request = client.recv(1000)
  puts request

  client.puts "HTTP/1.1 200 OK\nContent-Type: text/plain\n\nHello, World!"
  client.close
end
221 chars
13 lines

This code listens for incoming connections on port 8080, reads the request from the client, sends a HTTP response with a plain text content type, and closes the connection. The response body is "Hello, World!" which can be changed to any other text.

related categories

gistlibby LogSnag