Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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