-
-
Save jacqueline-homan/bcdb059d629f247965eb to your computer and use it in GitHub Desktop.
This file contains hidden or 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.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