Http Server in Haskell

Here’s the translation of the HTTP Server example from Go to Haskell, formatted in Markdown suitable for Hugo:

import Network.Wai
import Network.HTTP.Types
import Network.Wai.Handler.Warp
import Data.ByteString.Lazy.Char8 (pack)

-- A fundamental concept in Wai servers is
-- Application. An Application is a function that takes
-- a Request and returns a Response. This is similar to
-- the concept of handlers in other web frameworks.

hello :: Application
hello _ respond = respond $ responseLBS
    status200
    [("Content-Type", "text/plain")]
    "hello\n"

headers :: Application
headers request respond = respond $ responseLBS
    status200
    [("Content-Type", "text/plain")]
    (pack $ unlines $ map (\(name, values) -> show name ++ ": " ++ show values) $ requestHeaders request)

-- We combine our handlers into a single Application using
-- the `choose` function from Network.Wai.

app :: Application
app = choose [ ("/hello", hello)
             , ("/headers", headers)
             ]

main :: IO ()
main = do
    putStrLn "Starting server on port 8090..."
    run 8090 app

Writing a basic HTTP server in Haskell can be done using the wai and warp packages. The wai package provides a common interface for web applications, while warp is a high-performance HTTP server.

In Haskell, we define handlers as functions of type Application. An Application takes a Request and a response function, and returns an IO (). The response function is used to send the response back to the client.

The hello handler simply responds with “hello\n”.

The headers handler reads all the HTTP request headers and echoes them into the response body.

We combine our handlers into a single Application using the choose function, which routes requests based on the path.

Finally, we use the run function from warp to start the server on port 8090.

To run the server:

$ runhaskell http-server.hs
Starting server on port 8090...

You can then access the /hello route:

$ curl localhost:8090/hello
hello

This Haskell implementation provides similar functionality to the original example, using idiomatic Haskell constructs and the WAI (Web Application Interface) standard.