You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
importjwtfrom"jsonwebtoken";// Use um bundler para incluir dependências externas, se necessário.addEventListener("fetch",(event)=>{event.respondWith(handleRequest(event.request));});asyncfunctionhandleRequest(request){consturl=newURL(request.url);if(url.pathname==="/"){returnnewResponse("Welcome to the API!",{status: 200});}if(url.pathname.startsWith("/hello/")){constname=url.pathname.split("/")[2];returnnewResponse(`Hello, ${name}!`,{status: 200});}if(url.pathname==="/auth"){constauthHeader=request.headers.get("Authorization");if(!authHeader||!authHeader.startsWith("Bearer ")){returnnewResponse("Unauthorized",{status: 401});}consttoken=authHeader.split(" ")[1];try{constpayload=jwt.verify(token,"your-secret-key");returnnewResponse(`Hello, ${payload.name}!`,{status: 200});}catch{returnnewResponse("Invalid token",{status: 401});}}if(url.pathname==="/external"){constresponse=awaitfetch("https://api.github.com/repos/cloudflare/workers");constdata=awaitresponse.json();returnnewResponse(JSON.stringify({stars: data.stargazers_count}),{headers: {"Content-Type": "application/json"},});}returnnewResponse("Not Found",{status: 404});}
Same logic but using HonoJS
import{Hono}from"hono";import{jwt}from"hono/jwt";constapp=newHono();// Rota simplesapp.get("/",(c)=>c.text("Welcome to the API!"));// Rota com parâmetro dinâmicoapp.get("/hello/:name",(c)=>{constname=c.req.param("name");returnc.text(`Hello, ${name}!`);});// Middleware para autenticação JWTconstsecretKey="your-secret-key";app.use("/auth/*",jwt({secret: secretKey}));app.get("/auth/user",(c)=>{constuser=c.get("user");returnc.json({message: `Hello, ${user.name}!`});});// Integração com API externaapp.get("/external",async(c)=>{constresponse=awaitfetch("https://api.github.com/repos/cloudflare/workers");constdata=awaitresponse.json();returnc.json({stars: data.stargazers_count});});exportdefaultapp;