custom http file service

This commit is contained in:
King Wang 2021-06-29 23:58:50 +08:00
parent ddc8ecdf49
commit 8bef4c845a
2 changed files with 15 additions and 7 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

View File

@ -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;
}