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 { 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;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user