Skip to content

Instantly share code, notes, and snippets.

@DanThiffault
Last active December 12, 2022 04:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DanThiffault/f8833eac6a08ea2c9595 to your computer and use it in GitHub Desktop.
Save DanThiffault/f8833eac6a08ea2c9595 to your computer and use it in GitHub Desktop.
Simple F# Web Server
open System
open System.Net
open System.Text
open System.IO
// Modified from http://sergeytihon.wordpress.com/2013/05/18/three-easy-ways-to-create-simple-web-server-with-f/
// download this file to your root directory and name as ws.fsx
// run with `fsi --load:ws.fsx`
// visit http://localhost:8080
let siteRoot = @"."
let defaultFile = "index.html"
let host = "http://localhost:8080/"
let listener (handler:(HttpListenerRequest->HttpListenerResponse->Async<unit>)) =
let hl = new HttpListener()
hl.Prefixes.Add host
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 getFileNameWithDefault (req:HttpListenerRequest) =
let relPath = Uri(host).MakeRelativeUri(req.Url).OriginalString
if (String.IsNullOrEmpty(relPath))
then Path.Combine(siteRoot, defaultFile)
else Path.Combine(siteRoot, relPath)
listener (fun req resp ->
async {
let fileName = getFileNameWithDefault req
if (File.Exists fileName)
then
let output = File.ReadAllText(fileName)
let txt = Encoding.ASCII.GetBytes(output)
resp.ContentType <- System.Web.MimeMapping.GetMimeMapping(fileName)
resp.OutputStream.Write(txt, 0, txt.Length)
resp.OutputStream.Close()
else
resp.StatusCode <- 404
let output ="File not found"
let txt = Encoding.ASCII.GetBytes(output)
resp.ContentType <- "text/plain"
resp.OutputStream.Write(txt, 0, txt.Length)
resp.OutputStream.Close()
})
@jonas1ara
Copy link

ERROR: The value, constructor, namespace or type 'MimeMapping' is not defined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment