Skip to content

Commit 7c4207a

Browse files
authored
docs: add deno server example to the README (#57)
1 parent 5397427 commit 7c4207a

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,42 @@ wsServer.on('connection', (ws) => {
582582
httpServer.listen(8080);
583583
```
584584

585+
### HTTP server on Deno
586+
```ts
587+
import {
588+
newHttpBatchRpcResponse,
589+
newWebSocketRpcSession,
590+
RpcTarget,
591+
} from "npm:capnweb";
592+
593+
// This is the server implementation.
594+
class MyApiImpl extends RpcTarget implements MyApi {
595+
// ... define API, same as above ...
596+
}
597+
598+
Deno.serve(async (req) => {
599+
const url = new URL(req.url);
600+
if (url.pathname === "/api") {
601+
if (req.headers.get("upgrade") === "websocket") {
602+
const { socket, response } = Deno.upgradeWebSocket(req);
603+
socket.addEventListener("open", () => {
604+
newWebSocketRpcSession(socket, new MyApiImpl());
605+
});
606+
return response;
607+
} else {
608+
const response = await newHttpBatchRpcResponse(req, new MyApiImpl());
609+
// If you are accepting WebSockets, then you might as well accept cross-origin HTTP, since
610+
// WebSockets always permit cross-origin request anyway. But, see security considerations
611+
// for further discussion.
612+
response.headers.set("Access-Control-Allow-Origin", "*");
613+
return response;
614+
}
615+
}
616+
617+
return new Response("Not Found", { status: 404 });
618+
});
619+
```
620+
585621
### HTTP server on other runtimes
586622

587623
Every runtime does HTTP handling and WebSockets a little differently, although most modern runtimes use the standard `Request` and `Response` types from the Fetch API, as well as the standard `WebSocket` API. You should be able to use these two functions (exported by `capnweb`) to implement both HTTP batch and WebSocket handling on all platforms:

0 commit comments

Comments
 (0)