Erste Schritte für Server

This commit is contained in:
2024-01-27 10:31:46 +01:00
parent 6bb99d58b6
commit 271c75c2e8
16 changed files with 242 additions and 0 deletions

View File

@@ -0,0 +1,62 @@
import { existsSync, readFileSync } from 'node:fs';
import { www_folder, index_alias } from './Webserver';
class Mapping {
ending: string;
encoding: string;
}
const mappings: Mapping[] = [
{ ending: 'html', encoding: 'text/html' },
{ ending: 'js', encoding: 'text/javascript' },
{ ending: 'css', encoding: 'text/css' },
{ ending: 'json', encoding: 'application/json' },
{ ending: 'ico', encoding: 'image/x-icon' },
{ ending: 'svg', encoding: 'image/svg+xml' },
{ ending: 'txt', encoding: 'text/plain' },
]
export class File {
type: string;
content: Buffer;
constructor(type: string, content: Buffer) {
this.content = content;
this.type = type;
}
}
export function file_allowed(url: string): boolean {
let allowed: boolean = false;
let m = url.match('\\.\\.');
if (m == null) {
allowed = true;
}
return allowed;
}
export function file_exists(url: string): boolean {
if(url == '/') {
url = index_alias;
}
return existsSync(www_folder + url);
}
export function file_get(url: string): File {
if(url == '/') {
url = index_alias;
}
return new File(get_type(url), readFileSync(www_folder + url));
}
function get_type(url: string): string {
if(url == '/') {
url = index_alias;
}
let type: string = 'application/octet-stream';
let m: Mapping = mappings.find((e) => e.ending == url.split('.').pop());
if(m != undefined) {
type = m.encoding;
}
return type;
}

View File

@@ -0,0 +1,19 @@
import { IncomingMessage, ServerResponse } from "node:http";
import { file_allowed, file_exists, file_get, File } from "./FileHandler";
export function new_request(req: IncomingMessage, res: ServerResponse): void {
if(file_allowed(req.url)) {
if(file_exists(req.url)) {
res.statusCode = 200;
let f: File = file_get(req.url)
res.setHeader('Content-Type', f.type);
res.end(f.content);
} else {
res.statusCode = 404;
}
} else {
res.statusCode = 403;
}
console.log(req.url, res.statusCode);
res.end();
}

View File

@@ -0,0 +1,18 @@
import { createServer } from 'node:http'
import { new_request } from './RequestHandler';
export const www_folder: string = '/home/carsten/Dokumente/SmartHomeDashboard/html/';
export const index_alias: string = 'index.html';
const port: number = 8080;
const hostname: string = '127.0.0.1';
export function start_server(): void {
const server = createServer(new_request);
server.listen(port, hostname, () => {
console.log('Server running at http://' + hostname + ':' + port);
});
}

4
Server/server/main.ts Normal file
View File

@@ -0,0 +1,4 @@
import { start_server } from "./Webserver";
start_server();
console.log("Server started");