Servest has similar api to std/http. Easy to migrate your code into servest.
import { serve } from "https://deno.land/std/http/mod.ts";
const server = serve({ port: 8888 });
for await (const req of server) {
await req.respond({
status: 200,
headers: new Headers({
"content-type": "text/plain",
}),
body: "hello deno!",
});
}
import { createApp } from "https://servestjs.org/@v1.1.7/mod.ts";
const app = createApp();
app.handle("/", async (req) => {
await req.respond({
status: 200,
headers: new Headers({
"content-type": "text/plain",
}),
body: "hello deno!",
});
});
app.listen({ port: 8888 });
Servest provides many shorthands to handle HTTP request.
import { serve } from "https://deno.land/std/http/mod.ts";
const server = serve({ port: 8888 });
for await (const req of server) {
if (
req.method === "POST" &&
req.url === "/post"
) {
const buf = new Deno.Buffer();
await Deno.copy(req.body, buf);
const decoder = new TextDecoder();
const str = decoder.decode(buf.bytes());
const json = JSON.parse(str);
// handling...
} else {
req.respond({ status: 404 });
}
}
import { createApp } from "https://servestjs.org/@v1.1.7/mod.ts";
const app = createApp();
app.post("/post", async (req) => {
const body = await req.json();
// handling...
});
Make your real-time application with several lines of code.
import { serve } from "https://deno.land/std/http/mod.ts";
import { acceptable, acceptWebSocket } from "https://deno.land/std/ws/mod.ts";
const server = serve({ port: 8888 });
for await (const req of server) {
if (
req.method === "GET" &&
req.url === "/ws" &&
acceptable(req)
) {
acceptWebSocket({
headers: req.headers,
conn: req.conn,
bufWriter: req.w,
bufReader: req.r,
}).then(async (sock) => {
for await (const msg of sock) {
if (typeof msg === "string") {
// handle messages...
}
}
}).catch((e) => {
req.respond({ status: 400 });
});
} else {
req.respond({ status: 404 });
}
}
import { createApp } from "https://servestjs.org/@v1.1.7/mod.ts";
const app = createApp();
app.ws("/ws", async (sock) => {
for await (const msg of sock) {
if (typeof msg === "string") {
// handle messages...
}
}
});
Servest supports jsx/tsx with zero configurations.
// @deno-types="https://servestjs.org/@v1.1.7/types/react/index.d.ts"
import React from "https://dev.jspm.io/react/index.js";
// @deno-types="https://servestjs.org/@v1.1.7/types/react-dom/server/index.d.ts"
import ReactDOMServer from "https://dev.jspm.io/react-dom/server.js";
import { createApp } from "https://servestjs.org/@v1.1.7/mod.ts";
const app = createApp();
app.handle("/", async (req) => {
await req.respond({
status: 200,
headers: new Headers({
"content-type": "text/html; charset=UTF-8",
}),
body: ReactDOMServer.renderToString(
<html>
<head>
<meta charSet="utf-8" />
<title>servest</title>
</head>
<body>Hello Servest!</body>
</html>,
),
});
});
app.listen({ port: 8899 });