Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Basic Nowin self host. No dependencies on Microsoft.Owin.* assemblies.
open System
open System.IO
open System.Net
open System.Collections.Generic
open System.Threading.Tasks
let port = 8888
let endWithCompletedTask = fun x -> Task.FromResult(null) :> Task
type OwinEnvironment = {
httpMethod: string;
requestBody: Stream;
responseBody: Stream;
setResponseStatusCode: (int -> unit);
setResponseReasonPhrase: (string -> unit)
}
let getOwinEnvironment (env: IDictionary<string, obj>) = {
httpMethod = env.["owin.RequestMethod"] :?> string;
requestBody = env.["owin.RequestBody"] :?> Stream;
responseBody = env.["owin.ResponseBody"] :?> Stream;
setResponseStatusCode =
fun (statusCode: int) -> env.["owin.ResponseStatusCode"] <- statusCode
setResponseReasonPhrase =
fun (reasonPhrase: string) -> env.["owin.ResponseReasonPhrase"] <- reasonPhrase
}
let transform (request: string) : string =
sprintf "%s transformed" request
let handleOwinEnvironment (owin: OwinEnvironment) : unit =
use writer = new StreamWriter(owin.responseBody)
match owin.httpMethod with
| "POST" ->
use reader = new StreamReader(owin.requestBody)
writer.Write(transform(reader.ReadToEnd()))
| _ ->
owin.setResponseStatusCode 400
owin.setResponseReasonPhrase "Bad Request"
writer.Write("Only POST requests are allowed")
[<EntryPoint>]
let main argv =
use server =
Nowin.ServerBuilder
.New()
.SetEndPoint(new IPEndPoint(IPAddress.Any, port))
.SetOwinApp(fun env ->
env
|> getOwinEnvironment
|> handleOwinEnvironment
|> endWithCompletedTask)
.Build()
server.Start()
printfn "Server listening on http://localhost:%i/ \nhit <enter> to stop." port
Console.ReadLine() |> ignore
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment