forked from esa/asn1scc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHttpServer.fs
48 lines (37 loc) · 1.43 KB
/
HttpServer.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
namespace Daemon
open System.Net
open System
type HttpServer(uri:string) =
let listener = new HttpListener()
let pathPrefix = (new Uri(uri.Replace("+", "localhost"))).AbsolutePath
do
listener.Prefixes.Add(uri)
let mutable stopRequested = false
let ExtractCommandPath (uriPath:string) =
if not (uriPath.StartsWith pathPrefix) then ""
else uriPath.Substring(pathPrefix.Length)
let handleRequest (context:HttpListenerContext) handlers = async {
try
let handler = handlers (ExtractCommandPath context.Request.Url.AbsolutePath)
handler context
context.Response.Close()
with
| _ -> Http.SendError context.Response HttpStatusCode.InternalServerError
}
member this.Serve handlers =
listener.Start()
stopRequested <- false
let asynctask = Async.FromBeginEnd(listener.BeginGetContext,listener.EndGetContext)
async {
while not stopRequested do
try
let! context = asynctask
Async.Start (handleRequest context handlers)
with
| :? HttpListenerException -> ()
} |> Async.RunSynchronously
member this.Stop =
stopRequested <- true
listener.Stop()
member this.SendNotFound (context:HttpListenerContext) =
Http.SendError context.Response HttpStatusCode.NotFound