4 ms·
I like the first code example on https://crystal-lang.org https://crystal-lang.org # A very basic HTTP server require "http/server" server = HTTP:
by mg 3y ago
I like the first code example on https://crystal-lang.org https://crystal-lang.org
# A very basic HTTP server
require "http/server"
server = HTTP::Server.new do |context|
context.response.content_type = "text/plain"
context.response.print "Hello world, got #{context.request.path}!"
end
puts "Listening on http://127.0.0.1:8080"
server.listen(8080)
Nicely concise!
This would be the Python equivalent:
# A very basic HTTP server
from http.server import BaseHTTPRequestHandler, HTTPServer
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(bytes(f"Hello world, got {self.path}!", 'utf8'))
httpd = HTTPServer(('', 8080), RequestHandler)
print("Listening on http://127.0.0.1:8080")
httpd.serve_forever()
Would like to see it in more languages.
- alwaysbeconsing 3y agoWould not Ruby be the comparison to do? In which case it I think is nearly identical to the Crystal.
- doublerabbit 3y agoTCL: proc webServer {chan addr port} { while {[gets $chan] ne ""} {} puts $chan "HTTP/1.1 200 OK\n Connection: close\nContent-Type: text/plain\n" puts $chan "Hello World!" close $chan } socket -server webServer 8080 vwait forever
- mg 3y agoThat lacks a few things: 1: The comment 2: Printing the status message ("Listening on ...") 3: Outputting "Hello world, got {request.path}!" Aka http request parsing and string extrapolation.
- ReleaseCandidat 3y agoHaskell with WAI (more or less, guess there is some conversion from `Bytestring` needed when using `rawPathInfo`) {-# LANGUAGE OverloadedStrings #-} import Network.HTTP.Types import Network.Wai import Network.Wai.Handler.Warp (run) app :: Application app request respond = do respond $ responseLBS status200 [("Content-Type", "text/plain")] ("Hello world, got" <> rawPathInfo request <> "!") main :: IO () main = do putStrLn "Listening on http://127.0.0.1:8080" run 8080 app
- deleted 3y ago[deleted]
- beanaroo 3y agoNot exactly the same but various basic HTTP server implementations are presented at https://rosettacode.org/wiki/Hello_world/Web_server https://rosettacode.org/wiki/Hello_world/Web_server
- deleted 3y ago[deleted]