Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module Server
- [<EntryPoint>]
- let main argv =
- let port = 8080
- //Use svarende til C#, kalder dispose ved GB
- use hl = new System.Net.HttpListener ()
- hl.Prefixes.Add <| sprintf "http://+:%d/" port //%d inserts port intro string
- //Starting server
- hl.Start ()
- //Server loop for handling requests
- let rec loop () =
- let ctx = hl.GetContext()
- let request = ctx.Request
- let response = ctx.Response
- let meth = request.HttpMethod
- let path = request.RawUrl
- let rip = request.RemoteEndPoint.Address
- let rport = request.RemoteEndPoint.Port
- //Waiting for incomming HTTP Requests
- let body =
- use is = new System.IO.StreamReader(request.InputStream, request.ContentEncoding)
- is.ReadToEnd()
- //Eg "Create /resorce/C from ::1 57916 [data]"
- printfn "%s %s from %s %d [%s]" meth path (rip.ToString()) rport body
- //Function for sending a reply, calls loop recusive
- //Mangler at have en globalstate/store er sendes rundt
- let reply answer status reason =
- printfn "--> %d %s %s" status reason answer //Prints response to shell
- //Sets responsevalues "imperative"
- response.StatusCode <- status
- response.StatusDescription <- reason
- //Transforms answer string -> byte []
- let buffer = System.Text.Encoding.UTF8.GetBytes(answer)
- response.ContentLength64 <- int64 buffer.Length
- response.OutputStream.Write(buffer, 0, buffer.Length)
- response.OutputStream.Close();
- loop ()
- match meth with
- | "GET" -> reply "Handling Get" 200 "OK"
- | "PUT" -> reply "Handling Put" 200 "OK"
- | "DELETE" -> reply "Handling Delete" 200 "OK"
- | "CREATE" -> reply "Handling Create" 200 "OK"
- //Starting loop
- loop ()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement