Haffle, a Haskell HTTP Server

When I program in my spare time, I usually do enough work to cover all of the interesting parts, and then abandon the project to move onto something new. I guess this is because I put more of a focus on the problem than the finished result.

Because of this, it’s something of a pleasant surprise that I am continuing to work on my Haskell HTTP server over a month after I started on it. I’ve decided on a name, Haffle, and I’ve just finished version 0.0.3. Haffle 0.0.3 can read POST variables and GET query strings, so it’s starting to become almost useful.

I suspect I’ve gotten so far, because Haskell is such an interesting language. There’s very little tedium involved in Haskell, and you can produce a lot of functionality in a very small amount of code. It’s a language that’s very much suited to dipping in and out. There have been times when I’ve only fiddled with parts of it for half an hour or so, yet still produced something useful and concrete.

Anyway, here’s a working sample application using Haffle 0.0.3. Hopefully the code should be pretty self explanatory. When executed, it creates a server on port 8080.

module Main where
import Haffle
 
main = httpServe 8080 $ do
    path <- getPath
    case path of
        "/"      -> form
        "/greet" -> greet
        _        -> setStatus 404 >> outputLn "<h1>Page not found</h1>"
 
form = do
    outputLn "<form method=\"post\" action=\"/greet\">"
    outputLn "<label for=\"name\">Enter your name:</label>"
    outputLn "<input id=\"name\" name=\"name\" type=\"text\">"
    outputLn "<input type=\"submit\" value=\"Send\">"
    outputLn "</form>"
 
greet = do
    name <- getParam "name"
    case name of
        Nothing -> outputLn $ "<h3>Eh? What was your name, again?</h3>"
        Just n  -> outputLn $ "<h3>Hello " ++ n ++ "!</h3>"