Creating a simple HTTP Server with F#
Following on from Doug’s post about Double Meta Refresh; we found it is quite handy to be able to visually test what the referrer is when visiting a link.
Again, I call on my favourite language – F# – for doing quick scripts and utilities!
open System open System.Net open System.Text let listener (handler:(HttpListenerRequest -> HttpListenerResponse -> Async<unit>)) = let hl = new HttpListener() hl.Prefixes.Add "http://*:8080/" hl.Start() let task = Async.FromBeginEnd(hl.BeginGetContext, hl.EndGetContext) async { while true do let! context = task Async.Start(handler context.Request context.Response) } |> Async.Start let output (req:HttpListenerRequest) = if req.UrlReferrer = null then "No referrer!" else "Referrer: " + req.UrlReferrer.ToString() listener (fun req resp -> async { let txt = Encoding.ASCII.GetBytes(output req) resp.OutputStream.Write(txt, 0, txt.Length) resp.OutputStream.Close() }) printfn "Press return to exit..." Console.ReadLine() |> ignore
At the top we have a function called listener which takes in a handler function clearly shown as the type HttpListenerRequest -> HttpListenerResponse -> Async<unit>
If you’ve ever used HttpListener before, then you may recognise the code in the body of the listener function. It sets up then starts the HttpListener and creates an Async task for the HttpListener. Finally, we pass an anonymous function to listener which simply writes to the response output stream with the text from the output function just above it.
The last few lines are required only if you compile the code. It simply ensures the console application does not exit immediately; if you’re pasting this example into F# Interactive, you can skip them.
Read more posts about F#:
Comments
Latest from B3Labs
- Another milestone reached for Branded3 as it’s acquired by the
St Ives Group - The latest media consumer findings & what they mean for digital marketers
- Talk to Branded3 at @BuyYorkshire in Leeds next week!
Latest from Blogstorm
- After five years, Google still doesn’t know how to rank images
- Tickets now on sale for the next #B3Seminar in London – book now!
- Google Only Shows One Organic Result To iPad Users