-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.wls
80 lines (63 loc) · 2.17 KB
/
server.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
Print @ "Wolfram Expression Server 0.0.1 (alpha)";
Print @ "Usage: wolframserver.wls [port]\n";
Needs["CodeFormatter`"];
(* https://github.com/WolframResearch/codeformatter/issues/3 *)
CodeFormatter`$DefaultLineWidth = 120;
(* https://github.com/WolframResearch/codeformatter/issues/4#issuecomment-1297455149 *)
SetOptions[CodeFormatter`CodeFormatCST, CodeFormatter`Airiness -> -0.75, CodeFormatter`BreakLinesMethod -> "LineBreakerV2"];
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 = CodeFormatter`CodeFormat[request["Body"]];
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..."];