Created
October 31, 2025 18:06
-
-
Save jhawthorn/f172fe4b8c94d0b013936f6b28351f80 to your computer and use it in GitHub Desktop.
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
| # frozen_string_literal: true | |
| require "socket" | |
| require "picohttp" | |
| class App | |
| def call(env) | |
| path = env["PATH_INFO"] | |
| route = ROUTES[path] | |
| if route | |
| text = route.call | |
| [200, {}, [text]] | |
| else | |
| [404, {}, ["not found"]] | |
| end | |
| end | |
| ROUTES = {} | |
| def self.get(path, &block) | |
| ROUTES[path] = Ractor.shareable_proc(&block) | |
| end | |
| HIT_COUNTER = Ractor.new do | |
| count = 0 | |
| loop do | |
| response = Ractor.receive | |
| count += 1 | |
| response << count | |
| puts count | |
| end | |
| end | |
| get("/") do | |
| port = Ractor::Port.new | |
| HIT_COUNTER.send(port) | |
| counter = port.receive | |
| "Thank you for visiting my web zone user ##{counter}" | |
| end | |
| ROUTES.freeze | |
| end | |
| def handle_request(app, fd) | |
| request_ractor = Ractor.new(app, fd) do |app, fd| | |
| s = IO.for_fd(fd) | |
| s.autoclose = true | |
| headers = s.gets("\r\n\r\n") | |
| env = Picohttp.parse_request_env(headers) | |
| status, headers, body = app.call(env) | |
| s.print("HTTP/1.0 #{status}\r\n") | |
| headers.each do |key, value| | |
| s.print("#{key}: #{value}\r\n") | |
| end | |
| #s.print("Connection: close\r\n") | |
| s.print("\r\n") | |
| body.each do | |
| s.print(it) | |
| end | |
| ensure | |
| s.close | |
| end | |
| end | |
| server = TCPServer.new("127.0.0.1", 8080) | |
| accept_ractor = Ractor.new(server) do |server| | |
| app = Ractor.make_shareable(App.new) | |
| while sockfd = server.sysaccept | |
| handle_request(app, sockfd) | |
| end | |
| end.join |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment