Last active
December 12, 2022 04:52
-
-
Save DanThiffault/f8833eac6a08ea2c9595 to your computer and use it in GitHub Desktop.
Simple F# Web Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ERROR: The value, constructor, namespace or type 'MimeMapping' is not defined.