-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathwolframserver.wls
executable file
·45 lines (37 loc) · 1.59 KB
/
wolframserver.wls
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
#!/usr/bin/env wolframscript
Print @ "Wolfram Expression Server 0.0.1 (alpha)";
Print @ "Usage: wolframserver.wls [port]\n";
If[ Length[$ScriptCommandLine] == 2, port = ToExpression @ Part[$ScriptCommandLine,2], port = 5858 ];
Print["Port: ", port];
Print["$ProcessID: ", $ProcessID];
ApacheDateString[] := With[{tz = StringReplace[DateString["ISOTimeZone"], ":" -> ""]},
DateString[{"[", "Day", "/", "Month", "/", "Year", ":", "Hour", ":", "Minute", ":", "Second", " ", tz, "]"}]];
ApacheLog[ str_String ] := Module[{}, Print[ "127.0.0.1 - - " <> ApacheDateString[] <> " \"POST / HTTP/1.1\" 200 " <> StringTrim[str] ] ];
listener = SocketListen[
port,
Function[{assoc},
With[{
client = assoc["SourceSocket"],
data = assoc["Data"]
},
request = ImportString[data, "HTTPRequest"];
origin = Association[ request["Headers"] ]["origin"];
If[ Head[origin]===Missing, origin="" ];
result = ExportString[ ToExpression[ request["Body"], StandardForm ], "ExpressionJSON" ];
response = ExportString[
HTTPResponse[ result, <|
"StatusCode" -> 200,
"ContentType" -> "application/json",
"Headers" -> { "Access-Control-Allow-Origin" -> origin }
|>], "HTTPResponse"];
WriteString[client, response];
ApacheLog[ request["Body"] ];
Close[client]
]
]
];
url = URLBuild[<|"Scheme" -> "http", "Domain" -> First[listener["Socket"]["DestinationIPAddress"]], "Port" -> listener["Socket"]["DestinationPort"]|>];
Print["Listening: ", url, "\n"];
task = ZeroMQLink`Private`$AsyncState["Task"];
WaitAsynchronousTask[task];
Print["Exiting..."];