Created
February 8, 2020 07:17
-
-
Save willhbr/9e7fe7fe09b953f3a2549629860c4dee to your computer and use it in GitHub Desktop.
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 "http/server" | |
module MaybHTTP | |
VERSION = "0.1.0" | |
class ConcattedIO < IO | |
def initialize(@first : IO::Memory, @second : IO) | |
end | |
def read(bytes) | |
if @first.closed? | |
size = @second.read(bytes) | |
else | |
size = @first.read(bytes) | |
@first.close unless size == @first.size | |
end | |
size | |
end | |
def write(bytes) : Nil | |
@second.write(bytes) | |
end | |
end | |
abstract class Server < HTTP::Server | |
private def handle_client(io : IO) | |
prefix = Bytes.new(3) | |
io.read(prefix) | |
pre = String.new prefix | |
with_prefix = ConcattedIO.new(IO::Memory.new(pre), io) | |
if {"GET", "HEA", "POS", "PUT", "DEL", "CON", "OPT", "TRA"}.includes? pre | |
puts "handling http" | |
super with_prefix | |
else | |
handle_not_http(with_prefix) | |
end | |
end | |
abstract def handle_not_http(io : IO) | |
end | |
end | |
class TestServer < MaybHTTP::Server | |
def handle_not_http(io) | |
puts "starting not http" | |
io.puts "but but but but but" | |
puts io.gets_to_end | |
io.close | |
end | |
end | |
server = TestServer.new do |context| | |
context.response.content_type = "text/plain" | |
context.response.print "Hello world!" | |
end | |
server.bind_tcp "0", 8080 | |
puts "serving" | |
server.listen |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment