create a http server and parse cookies in ruby

main.rb
require 'socket'

port = 3000
server = TCPServer.new(port)

def parse_cookie(cookie_string)
  cookie_hash = {}
  cookies = cookie_string.split(';')
  cookies.each do |cookie|
    key, value = cookie.split('=').map{ |element| element.strip }
    cookie_hash[key] = value
  end
  cookie_hash
end

def respond(client, request)
  method, path = request.lines[0].split
  status = 200
  headers = {}
  body = ''

  if method == 'GET' && path == '/path'
    headers['Set-Cookie'] = 'user_id=123; expires=Wed, 21 Oct 2021 07:28:00 GMT'
    cookie = parse_cookie(request['Cookie'])
    body = "Hello user ##{cookie['user_id']}!"
  else
    status = 404
    body = "Not found\n"
  end

  headers['Content-Type'] = 'text/plain'
  headers['Content-Length'] = body.length
  headers['Connection'] = 'close'

  header = headers.map{ |key, value| "#{key}: #{value}" }.join("\r\n")

  response = "HTTP/1.1 #{status}\r\n#{header}\r\n\r\n#{body}"
  client.puts(response)
end

loop do
  client = server.accept
  request = client.gets

  respond(client, request)

  client.close
end
1062 chars
49 lines

This code creates a TCP server that listens on port 3000. When a request is received, it is parsed and the corresponding action is taken. If the request is a GET request to the /path route, a cookie is set and a response is sent back with a greeting that includes the user ID stored in the cookie, otherwise a 404 response is sent. The parse_cookie method is used to convert the cookie string to a hash.

gistlibby LogSnag