route.js 1.61 KB
Newer Older
wuhao's avatar
wuhao committed
1
// app/api/streaming/route.js
wuhao's avatar
wuhao committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
const story = [
  "李焊玲是一个女汉子。",
  "她力大无穷,",
  "喜欢挑战各种极限运动。",
  "有一天,",
  "她决定去攀登一座险峻的高山。",
  "在山脚下,",
  "她遇到了一群正准备放弃的登山者。",
  "李焊玲鼓励他们,",
  "说,",
  "只要坚持,",
  "没有什么是不可能的。",
  "于是,",
  "她带领这群登山者一起向山顶进发。",
  "一路上,",
  "她用自己的力量帮助大家克服各种困难,",
  "大家都被她的勇气和毅力所感染。",
  "最终,",
  "在李焊玲的带领下,",
  "他们成功登上了山顶。",
  "大家欢呼雀跃,",
  "李焊玲却笑着说,",
  "这只是人生中的一个小挑战,",
  "未来还有更多的冒险等着我们。",
  "从那以后,",
  "李焊玲的故事在登山者中广为流传,",
  "她成为了大家心目中的英雄。"
];



wuhao's avatar
wuhao committed
33 34 35 36 37

export async function GET(request) {
  const readable = new ReadableStream({
    async start(controller) {
      // 第一块数据
wuhao's avatar
wuhao committed
38
      // controller.enqueue("\n");
wuhao's avatar
wuhao committed
39 40 41

      // 模拟延迟并逐步发送数据块
      const encoder = new TextEncoder();
wuhao's avatar
wuhao committed
42
      
wuhao's avatar
wuhao committed
43 44
      for (let i = 0; i < story.length; i++) {
        await new Promise((resolve) => setTimeout(resolve, story[i].length*50));
wuhao's avatar
wuhao committed
45 46
        controller.enqueue(
          encoder.encode(
wuhao's avatar
wuhao committed
47
            `${story[i]} \n`
wuhao's avatar
wuhao committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
          )
        );
      }

      // 关闭流
      controller.close();
    },
  });

  return new Response(readable, {
    headers: {
      "Content-Type": "text/plain",
      "Transfer-Encoding": "chunked",
    },
  });
}