Skip to content

Instantly share code, notes, and snippets.

@brunos3d
Created March 26, 2025 17:19
Show Gist options
  • Save brunos3d/aec13d9efb5861a467eb74eea3ab9c89 to your computer and use it in GitHub Desktop.
Save brunos3d/aec13d9efb5861a467eb74eea3ab9c89 to your computer and use it in GitHub Desktop.

Simple example with a Pure CF Worker

import jwt from "jsonwebtoken"; // Use um bundler para incluir dependências externas, se necessário.

addEventListener("fetch", (event) => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const url = new URL(request.url);

  if (url.pathname === "/") {
    return new Response("Welcome to the API!", { status: 200 });
  }

  if (url.pathname.startsWith("/hello/")) {
    const name = url.pathname.split("/")[2];
    return new Response(`Hello, ${name}!`, { status: 200 });
  }

  if (url.pathname === "/auth") {
    const authHeader = request.headers.get("Authorization");
    if (!authHeader || !authHeader.startsWith("Bearer ")) {
      return new Response("Unauthorized", { status: 401 });
    }
    const token = authHeader.split(" ")[1];
    try {
      const payload = jwt.verify(token, "your-secret-key");
      return new Response(`Hello, ${payload.name}!`, { status: 200 });
    } catch {
      return new Response("Invalid token", { status: 401 });
    }
  }

  if (url.pathname === "/external") {
    const response = await fetch("https://api.github.com/repos/cloudflare/workers");
    const data = await response.json();
    return new Response(JSON.stringify({ stars: data.stargazers_count }), {
      headers: { "Content-Type": "application/json" },
    });
  }

  return new Response("Not Found", { status: 404 });
}

Same logic but using HonoJS

import { Hono } from "hono";
import { jwt } from "hono/jwt";

const app = new Hono();

// Rota simples
app.get("/", (c) => c.text("Welcome to the API!"));

// Rota com parâmetro dinâmico
app.get("/hello/:name", (c) => {
  const name = c.req.param("name");
  return c.text(`Hello, ${name}!`);
});

// Middleware para autenticação JWT
const secretKey = "your-secret-key";
app.use("/auth/*", jwt({ secret: secretKey }));

app.get("/auth/user", (c) => {
  const user = c.get("user");
  return c.json({ message: `Hello, ${user.name}!` });
});

// Integração com API externa
app.get("/external", async (c) => {
  const response = await fetch("https://api.github.com/repos/cloudflare/workers");
  const data = await response.json();
  return c.json({ stars: data.stargazers_count });
});

export default app;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment