Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

An example of HTTP server #681

Open
xna00 opened this issue Dec 23, 2024 · 1 comment
Open

An example of HTTP server #681

xna00 opened this issue Dec 23, 2024 · 1 comment

Comments

@xna00
Copy link

xna00 commented Dec 23, 2024

This is a simple HTTP server. Not support HTTP request body.

import getopts from 'tjs:getopts';
import { addr } from './utils.js';

function parseRequestLine(requestLine) {
    const [method, path] = requestLine.split(' ');
    return { method, path };
}

async function handleConnection(conn) {
    const buf = new Uint8Array(65536);
    let len = 0

    while (true) {
        const nread = await conn.read(buf);
        len += (nread || 0);
        const requestData = new TextDecoder().decode(buf.subarray(0, len));
        if (requestData.includes('\r\n\r\n')) {
            const [requestLine, ...headersLines] = requestData.split('\r\n');
            const { method, path } = parseRequestLine(requestLine);
            const headers = Object.fromEntries(headersLines.map(line => line.split(': ', 2)));
            
            const request = `Method: ${method}\nPath: ${path}\nHeaders: ${JSON.stringify(headers, null, 2)}`;
            console.log('Received request:');
            console.log(request);

            const response = `HTTP/1.1 200 OK\r\nContent - Type: text/html\r\n\r\n<html><body><pre>${request}</pre></body></html>`;
            conn.write((new TextEncoder().encode(response)));
            conn.close();
            break;
        }
    }
}

const options = getopts(tjs.args.slice(2), {
    alias: {
        listen: 'l',
        port: 'p'
    },
    default: {
        listen: '127.0.0.1',
        port: 1234
    }
});

const l = await tjs.listen('tcp', options.listen, options.port);

console.log(`Listening on http://${addr(l.localAddress)}`);

for await (let conn of l) {
    handleConnection(conn);
    conn = undefined;
}
@saghul
Copy link
Owner

saghul commented Dec 23, 2024

Nice, thanks for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants