feat: add first-class WebSocket support via ctx.upgrade() and app.ws() (#3774)
## Summary
- **`ctx.upgrade()`** on the `Context` class with two overloads:
- **Bare mode**: `ctx.upgrade()` or `ctx.upgrade(options)` returns `{
socket, response }` for manual event wiring
- **Managed mode**: `ctx.upgrade(handlers)` accepts `{ open, message,
close, error }` and returns the upgrade `Response` directly
- **`app.ws(path, handlers, options?)`** shorthand that registers a GET
route with automatic WebSocket upgrade (managed mode only)
- Both support `idleTimeout` and `protocol` options forwarded to
`Deno.upgradeWebSocket()`
- Throws `HttpError(400)` on non-WebSocket requests
- Case-insensitive `Upgrade` header check per RFC 6455 §4.2.1
- Exports `WebSocketHandlers` and `WebSocketUpgradeOptions` types from
`fresh`
- Full documentation page with examples for managed mode, bare mode,
broadcast chat, and client-side usage
This commit is contained in:
@@ -175,29 +175,8 @@ export const handler = define.handlers({
|
||||
|
||||
## WebSockets
|
||||
|
||||
Fresh runs on Deno, so you can upgrade HTTP connections to WebSockets directly:
|
||||
|
||||
```ts routes/api/ws.ts
|
||||
import { define } from "@/utils.ts";
|
||||
|
||||
export const handler = define.handlers({
|
||||
GET(ctx) {
|
||||
const { socket, response } = Deno.upgradeWebSocket(ctx.req);
|
||||
|
||||
socket.onopen = () => {
|
||||
console.log("Client connected");
|
||||
};
|
||||
socket.onmessage = (event) => {
|
||||
socket.send(`Echo: ${event.data}`);
|
||||
};
|
||||
socket.onclose = () => {
|
||||
console.log("Client disconnected");
|
||||
};
|
||||
|
||||
return response;
|
||||
},
|
||||
});
|
||||
```
|
||||
Fresh provides first-class WebSocket support via `ctx.upgrade()`. See the full
|
||||
[WebSocket guide](/docs/examples/websockets) for all options.
|
||||
|
||||
## Subdomain routing
|
||||
|
||||
|
||||
Reference in New Issue
Block a user