DEV Community

Cover image for 20-line of code HTTP server
Megabit
Megabit

Posted on

20-line of code HTTP server

Not Javascript, not Python, not Go, not PHP, no encapsulation.

Today I'm going to introduce a new coroutine language named Melang.

Melang logo

Melang is a coroutine concurrent scripting language. It is an interpreted, not compiled language.

In Melang, every script task is a coroutine. And multiple script tasks can be processed in the same thread or multithread at the same time.

This is very similar to Go's coroutines, but the coroutines in Melang do not need to actively give up CPU execution rights or call specific functions to indirectly give up CPU execution rights. Instead, the task execution is automatically switched after the interpreter performs certain operations. This also eliminates the need for developers to consider switching timing.

In Melang, all script code logic is synchronized. But it's actually done asynchronously by the interpreter. This help many developers who are not familiar with asynchronous programming to get started.

Here is a simple HTTP server example:

/* filename: server.m */
net = import('net');
mq = import('mq');

listenfd = net.tcp_listen('127.0.0.1', '80');
for (i = 0; i < 4; ++i)
    eval('worker.mln', i);
while (true) {
    fd = net.tcp_accept(listenfd);
    mq.send('test', fd);
}
Enter fullscreen mode Exit fullscreen mode
/* filename: worker.m */
sys = import('sys');
net = import('net');
mq = import('mq');

while (1) {
    fd = mq.recv('test');
    ret = net.tcp_recv(fd);
    if (ret) {
        net.tcp_send(fd, "HTTP/1.1 200 OK\r\nContent-Length: 1\r\n\r\na\r\n\r\n");
    } fi
    net.tcp_close(fd);
}
Enter fullscreen mode Exit fullscreen mode

The main coroutine (server.m) creates 4 worker coroutines (worker.m), and then enters an infinite loop waiting for the establishment of the client TCP.

The worker coroutine (worker.m) is in an infinite loop, receiving the established TCP socket from the main coroutine, then receiving the request from the TCP, then sending the HTTP response, and finally closing the socket.

Next, we can start the script from the command line with the following command:

$ melang server.m
Enter fullscreen mode Exit fullscreen mode

Once started, it can be accessed using tools like curl or ab.

Top comments (0)