diff --git a/examples/custom-http-res/res/test.png b/examples/custom-http-res/res/test.png new file mode 100644 index 0000000..73d8eb0 Binary files /dev/null and b/examples/custom-http-res/res/test.png differ diff --git a/examples/custom-http-res/src/index.ts b/examples/custom-http-res/src/index.ts index 8fed94d..ba933ad 100644 --- a/examples/custom-http-res/src/index.ts +++ b/examples/custom-http-res/src/index.ts @@ -1,4 +1,5 @@ -import * as path from "path"; +import fs from "fs/promises"; +import path from 'path'; import { HttpConnection, HttpServer } from "tsrpc"; import { serviceProto } from "./shared/protocols/serviceProto"; @@ -9,17 +10,24 @@ const server = new HttpServer(serviceProto, { }); // Custom HTTP Reponse -server.flows.preRecvBufferFlow.push(v => { +server.flows.preRecvBufferFlow.push(async v => { let conn = v.conn as HttpConnection; if (conn.httpReq.method === 'GET') { - // 特定 URL: /test - if (conn.httpReq.url === '/test') { - conn.httpRes.end('test test') - return undefined; + // Static File Service + if (conn.httpReq.url) { + // Check whether the file is existed + let resFilePath = path.join('res', conn.httpReq.url) + let isExisted = await fs.access(resFilePath).then(() => true).catch(() => false); + if (isExisted) { + // Response the file + let content = await fs.readFile(resFilePath); + conn.httpRes.end(content); + return undefined; + } } - // 默认 GET 响应 + // default GET response conn.httpRes.end('Hello World'); return undefined; }