Skip to content

Instantly share code, notes, and snippets.

@AngelMunoz
Last active December 5, 2021 19:52
Show Gist options
  • Save AngelMunoz/535838cc23bb394c1c1838f813b698a4 to your computer and use it in GitHub Desktop.
Save AngelMunoz/535838cc23bb394c1c1838f813b698a4 to your computer and use it in GitHub Desktop.
A sample of the scripting capabilities of F# 5.0
#r "nuget: Suave"
// 👆🏽 this was added in F# 5.0
// if you are using the .NET 5.0 previews or RC run as follows
// dotnet fsi suavefileexplorer.fsx --langversion:preview
open System
open System.IO
open System.Threading
open System.Text
open Suave
open Suave.Successful
open Suave.Operators
open Suave.RequestErrors
open Suave.Filters
let homepath =
// get the user's home dir
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
let fileExplorer (path: string): WebPart =
fun (ctx: HttpContext) ->
async {
let path = Path.GetFullPath($"{homepath}/{path}")
let dir = DirectoryInfo(path)
try
let directories = dir.EnumerateDirectories()
let files = dir.EnumerateFiles()
// format enumerated files and collections
let content =
$"""
<ul>
<li>
Directories:
<ul>
{ directories
// also known as [].reduce((prev, next => "", "") in javascript
|> Seq.fold (fun prev next -> prev + $"<li>{next.Name}</li>") "" }
</ul>
</li>
<li>
Files:
<ul>
{ files
// also known as [].reduce((prev, next => "", "") in javascript
|> Seq.fold (fun prev next -> prev + $"<li>{next.Name}</li>") "" }
</ul>
</li>
</ul>
"""
return! OK content ctx
with :? DirectoryNotFoundException as ex -> return! NOT_FOUND $"{ex.Message}" ctx
}
// define app routing
let app =
choose [ GET >=> pathScan "/%s" fileExplorer ]
let cts = new CancellationTokenSource()
let conf =
{ defaultConfig with
cancellationToken = cts.Token }
// start server with config and app
let listening, server = startWebServerAsync conf app
Async.Start(server, cts.Token)
printfn "Make requests now"
Console.ReadKey true |> ignore
cts.Cancel()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment