Skip to content

Instantly share code, notes, and snippets.

@sergey-tihon
Created May 25, 2013 05:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergey-tihon/5648075 to your computer and use it in GitHub Desktop.
Save sergey-tihon/5648075 to your computer and use it in GitHub Desktop.
open System
open System.Net
open System.Text
open System.IO
let siteRoot = @"D:\mySite\"
let host = "http://localhost:8080/"
let listener (handler:(HttpListenerRequest -> HttpListenerResponse -> Async<unit>)) cancellationToken =
let hl = new HttpListener()
hl.Prefixes.Add host
hl.Start()
let task = Async.FromBeginEnd(hl.BeginGetContext, hl.EndGetContext)
let loop =
async {
while true do
let! context = task
Async.Start(handler context.Request context.Response)
}
Async.Start(loop, cancellationToken)
let output (req:HttpListenerRequest) =
let file = Path.Combine(siteRoot,
Uri(host).MakeRelativeUri(req.Url).OriginalString)
printfn "Requested : '%s'" file
if (File.Exists file)
then File.ReadAllText(file)
else "File does not exist!"
let cancellableWork = new System.Threading.CancellationTokenSource()
listener (fun req resp ->
async {
let txt = Encoding.ASCII.GetBytes(output req)
resp.ContentType <- "text/html"
resp.OutputStream.Write(txt, 0, txt.Length)
resp.OutputStream.Close()
})
cancellableWork.Token
cancellableWork.Cancel()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment