custom http file service
This commit is contained in:
parent
ddc8ecdf49
commit
8bef4c845a
BIN
examples/custom-http-res/res/test.png
Normal file
BIN
examples/custom-http-res/res/test.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 28 KiB |
@ -1,4 +1,5 @@
|
|||||||
import * as path from "path";
|
import fs from "fs/promises";
|
||||||
|
import path from 'path';
|
||||||
import { HttpConnection, HttpServer } from "tsrpc";
|
import { HttpConnection, HttpServer } from "tsrpc";
|
||||||
import { serviceProto } from "./shared/protocols/serviceProto";
|
import { serviceProto } from "./shared/protocols/serviceProto";
|
||||||
|
|
||||||
@ -9,17 +10,24 @@ const server = new HttpServer(serviceProto, {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Custom HTTP Reponse
|
// Custom HTTP Reponse
|
||||||
server.flows.preRecvBufferFlow.push(v => {
|
server.flows.preRecvBufferFlow.push(async v => {
|
||||||
let conn = v.conn as HttpConnection;
|
let conn = v.conn as HttpConnection;
|
||||||
|
|
||||||
if (conn.httpReq.method === 'GET') {
|
if (conn.httpReq.method === 'GET') {
|
||||||
// 特定 URL: /test
|
// Static File Service
|
||||||
if (conn.httpReq.url === '/test') {
|
if (conn.httpReq.url) {
|
||||||
conn.httpRes.end('test test')
|
// Check whether the file is existed
|
||||||
return undefined;
|
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');
|
conn.httpRes.end('Hello World');
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user