-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathHttpServer.js
More file actions
92 lines (82 loc) · 2.74 KB
/
HttpServer.js
File metadata and controls
92 lines (82 loc) · 2.74 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
/*
import Gren.Kernel.Scheduler exposing (binding, succeed, fail, rawSpawn)
import HttpServer exposing (ServerError, toRequest)
import HttpServer.Response as Response exposing (toResponse)
import Platform exposing (sendToApp, sendToSelf)
*/
var _HttpServer_createServer = F2(function (host, port) {
return __Scheduler_binding(function (callback) {
const server = require("http").createServer();
server.on("error", function (e) {
callback(
__Scheduler_fail(
__HttpServer_ServerError({ __$code: e.code, __$message: e.message }),
),
);
});
server.listen(port, host, function () {
callback(__Scheduler_succeed(server));
});
});
});
var _HttpServer_addListener = F3(function (server, router, msg) {
server.on("request", function (request, response) {
// May want to support non-http protocols, proxies, and X-Forwarded-For header(s).
// Note: the `request` here is a node `http.IncomingMessage`, not a `http.ClientRequest`,
// so we can't just look at `request.protocol`, etc.
let url = new URL(request.url, `http://${request.headers.host}`);
let body = [];
request
.on("data", function (chunk) {
body.push(chunk);
})
// TODO: Timeouts.
// Currently, if the request never ends (because of an error, or...?)
// the server will hang until manually killed.
.on("end", function () {
const buffer = Buffer.concat(body);
let grenRequest = __HttpServer_toRequest({
__$url: url.href,
__$headers: request.rawHeaders,
__$method: request.method,
__$body: new DataView(
buffer.buffer,
buffer.byteOffset,
buffer.byteLength,
),
});
let grenResponse = __Response_toResponse(response);
__Scheduler_rawSpawn(
// May want to send to self, self sends to app instead.
// But effect handlers may be changing soon, so not bothering yet.
A2(__Platform_sendToApp, router, A2(msg, grenRequest, grenResponse)),
);
});
});
});
var _HttpServer_removeAllListeners = function (server) {
server.removeAllListeners("request");
};
var _HttpServer_setStatus = F2(function (status, res) {
res.statusCode = status;
return res;
});
var _HttpServer_setHeaders = F2(function (headers, res) {
headers.forEach(function (h) {
res.setHeader(h.__$key, h.__$value);
});
return res;
});
var _HttpServer_setBody = F2(function (body, res) {
res.write(body);
return res;
});
var _HttpServer_setBodyAsBytes = F2(function (data, res) {
let body = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
res.write(body);
return res;
});
var _HttpServer_endResponse = function (res) {
res.end();
return {};
};