-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathhttp-hello-world.js
More file actions
50 lines (45 loc) · 1.7 KB
/
http-hello-world.js
File metadata and controls
50 lines (45 loc) · 1.7 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
/**
* This module is the JS implementation of the `component` WIT world
*/
import {
ResponseOutparam,
OutgoingBody,
OutgoingResponse,
Fields,
} from 'wasi:http/[email protected]';
/**
* This export represents the `wasi:http/incoming-handler` interface,
* which describes implementing a HTTP handler in WebAssembly using WASI types.
*/
export const incomingHandler = {
/**
* This Javascript will be turned into a WebAssembly component by `jco` and turned into a
* WebAssembly binary with a single export (this `handler` function).
*
* The exported `handle` method is part of the `wasi:http/incoming-handler` interface,
* which defines how to hadle incoming web requests, turning this component into one that can
* serve web requests.
*/
handle(_incomingRequest, responseOutparam) {
// Start building an outgoing response
const outgoingResponse = new OutgoingResponse(new Fields());
// Access the outgoing response body
let outgoingBody = outgoingResponse.body();
{
// Create a stream for the response body
let outputStream = outgoingBody.write();
// Write hello world to the response stream
outputStream.blockingWriteAndFlush(
new Uint8Array(new TextEncoder().encode('Hello from Javascript!\n'))
);
// @ts-ignore: This is required in order to dispose the stream before we return
outputStream[Symbol.dispose]();
}
// Set the status code for the response
outgoingResponse.setStatusCode(200);
// Finish the response body
OutgoingBody.finish(outgoingBody, undefined);
// Set the created response to an "OK" Result<T> value
ResponseOutparam.set(responseOutparam, { tag: 'ok', val: outgoingResponse });
}
};