server

예제

const server = Bun.serve({
  // `routes` requires Bun v1.2.3+
  routes: {
    // Static routes
    "/api/status": new Response("OK"),

    // Dynamic routes
    "/users/:id": req => {
      return new Response(`Hello User ${req.params.id}!`);
    },

    // Per-HTTP method handlers
    "/api/posts": {
      GET: () => new Response("List posts"),
      POST: async req => {
        const body = await req.json();
        return Response.json({ created: true, ...body });
      },
    },

    // Wildcard route for all routes that start with "/api/" and aren't otherwise matched
    "/api/*": Response.json({ message: "Not found" }, { status: 404 }),

    // Redirect from /blog/hello to /blog/hello/world
    "/blog/hello": Response.redirect("/blog/hello/world"),

    // Serve a file by lazily loading it into memory
    "/favicon.ico": Bun.file("./favicon.ico"),
  },

  // (optional) fallback for unmatched routes:
  // Required if Bun's version < 1.2.3
  fetch(req) {
    return new Response("Not Found", { status: 404 });
  },
});

console.log(`Server running at ${server.url}`);

실행

# 자동으로 현재위치의 index 파일을 찾아서 실행함
bun .

bun index.ts

# 파일이 변경되면 리로드함
bun --watch index.ts

https 로 만들기

cerbot을 이용해서 인증서를 발급받아 https 로 통신하도록 한다.

공유기를 쓴다면 80포트가 포트포워딩 되어있어야 한다.

sudo apt install certbot -y

sudo certbot certonly --standalone -d dev.sixtick.net
// serve 에 적용 코드 . 소유자가 root임... 변경해줘야함
Bun.serve({
  port: 3443,
  tls: {
    cert: Bun.file("/etc/letsencrypt/live/dev.sixtick.net/fullchain.pem"),
    key: Bun.file("/etc/letsencrypt/live/dev.sixtick.net/privkey.pem"),
  },
  fetch(request) {
    return new Response("Secure Bun Server");
  }
});

만약 도커를 쓴다면 복사본의 소유권을 변경해서 넘겨주자

mkdir ./certs
sudo cp /etc/letsencrypt/live/dev.sixtick.net/fullchain.pem ./certs/
sudo cp /etc/letsencrypt/live/dev.sixtick.net/privkey.pem ./certs/
sudo chown -R 1000:1000 ./certs