DEV Community

greenServeFE
greenServeFE

Posted on

Exploring the server Module in greenServeFE

I've been spending time developing the server native module for greenServeFE. It has grown to include quite a few features, so I thought it would be useful to share what it can currently do and show how the APIs work together.

For anyone who hasn't come across greenServeFE before, it's a programming language and bytecode virtual machine written in C. It has its own lexer, parser, compiler, bytecode instructions, runtime values, and VM.

One thing I wanted to keep flexible was the way new features are added. Instead of introducing a new language keyword for every capability, greenServeFE can use native modules written in C. The server module is one example.

It provides HTTP server functionality, routing, middleware, response helpers, file handling, and an HTTP client. Here's a look at the current API.

Importing the module

Using the module is straightforward:

import server;

define details = server.info();

print(details);
Enter fullscreen mode Exit fullscreen mode

server.info() returns information about the module, including its version and supported features. The current version is 2.0.0.

Working with routes

Routes are registered by giving the server a path and a handler function. The module currently supports these registration functions:

API HTTP method
server.get(path, handler) GET
server.post(path, handler) POST
server.put(path, handler) PUT
server.patch(path, handler) PATCH
server.delete(path, handler) DELETE
server.options(path, handler) OPTIONS
server.any(path, handler) Any method
server.page(path, html) GET page
server.use(path, handler) Middleware

Here's a small example:

import server;

func home(req, res) {
    res.send("Hello from greenServeFE");
}

server.get("/", home);

server.serve(".", 8080);
Enter fullscreen mode Exit fullscreen mode

A route handler receives two arguments: req for the incoming request and res for the response.

Routes can also contain parameters. For example:

func user(req, res) {
    res.json({
        id: req.params.id,
        message: "User found"
    });
}

server.get("/users/:id", user);
Enter fullscreen mode Exit fullscreen mode

If someone visits /users/42, the value 42 is available through req.params.id.

There's also wildcard matching using *. The matched wildcard value can be accessed through req.params.wildcard.

Getting information from a request

The req object contains the information received from the client.

Property Description
req.method HTTP method
req.path Request path
req.queryString Original query string
req.query Parsed query parameters
req.params Route parameters
req.body Request body as text
req.form Parsed URL-encoded form fields
req.cookies Parsed request cookies
req.headers Request headers
req.contentType Content-Type header
req.isJson Whether the request content type is JSON
req.isAjax Whether X-Requested-With is XMLHttpRequest

For example, a search route can read a query parameter like this:

func search(req, res) {
    res.json({
        term: req.query.term,
        method: req.method,
        path: req.path
    });
}

server.get("/search", search);
Enter fullscreen mode Exit fullscreen mode

A request to /search?term=compiler makes compiler available as req.query.term.

The same idea applies to form submissions and cookies. URL-encoded form fields are available through req.form, while incoming cookies can be read from req.cookies.

Sending responses

The res object provides methods for building the response. These are the methods currently available:

API Purpose
res.status(code) Set the HTTP status
res.set(name, value) Set a response header
res.header(name, value) Set a response header
res.cookie(name, value, age?, secure?) Set a cookie
res.clearCookie(name) Clear a cookie
res.type(contentType) Set the content type
res.send(value) Send a value or JSON-serialize a non-string value
res.text(value) Send plain text
res.noContent() Send an empty 204 response
res.json(value) Send JSON
res.jsonp(value, callback) Send JSONP
res.html(html) Send HTML
res.redirect(url) Redirect the client
res.sendFile(path) Send a file relative to the server root
res.download(path, filename?) Send a file as an attachment
res.render(template, data?) Render a template file

For example, here's a route that returns a JSON response and adds a custom header:

func profile(req, res) {
    res.status(200);
    res.set("X-Powered-By", "greenServeFE");

    res.json({
        name: "greenServeFE",
        language: "greenServe",
        implementation: "C"
    });
}

server.get("/profile", profile);
Enter fullscreen mode Exit fullscreen mode

I wanted these response helpers to be usable directly inside route handlers, without needing to build the HTTP response manually each time.

Using middleware

Middleware is useful when you want to run some code before a route handler. It's registered with server.use(path, handler).

A middleware function receives three arguments: req, res, and next.

func middleware(req, res, next) {
    res.set("X-Application", "greenServeFE");
    next();
}

server.use("/", middleware);
Enter fullscreen mode Exit fullscreen mode

The important part is next(). It tells the server to continue to the next middleware or route. If middleware sends a response or doesn't call next(), the chain stops.

Middleware runs in registration order, and the server uses matching path prefixes to decide which middleware applies.

For example, this middleware is registered for paths under /api:

func api_middleware(req, res, next) {
    res.set("X-API-Version", "1");
    next();
}

server.use("/api", api_middleware);
Enter fullscreen mode Exit fullscreen mode

Making HTTP requests

The server module isn't only for receiving requests. It also has an HTTP client, so a greenServeFE program can make outgoing requests.

API Purpose
server.request(method, url, body?, headers?) General HTTP request
server.http_get(url) GET request
server.https_get(url) HTTPS GET request
server.http_post(url, body) POST request
server.http_put(url, body?, headers?) PUT request
server.http_patch(url, body?, headers?) PATCH request
server.http_delete(url, body?, headers?) DELETE request
server.http_options(url, body?, headers?) OPTIONS request

The general server.request() function accepts the HTTP method, URL, an optional body, and optional headers.

The returned object contains:

  • status — HTTP response status code
  • body — Response body
  • contentType — Response content type
  • url — Effective URL after redirects
  • headers — Response headers
  • error — Error message, or an empty string on success

Here's a simple GET request:

import server;

define response = server.http_get("https://example.com");

print(response.status);
print(response.contentType);
print(response.body);
print(response.error);
Enter fullscreen mode Exit fullscreen mode

The client uses libcurl. TLS certificate and hostname verification are enabled, redirects are limited, and connection and total request timeouts are configured.

A few more utilities

There are some additional functions that don't belong directly to routing or response handling.

API Description
server.read_file(path) Read a file as text
server.write_file(path, content) Write text to a file
server.render(template, data) Replace template placeholders with object values
server.url_encode(text) URL-encode text
server.json_escape(text) Escape characters for JSON strings
server.clear_routes() Remove registered routes
server.info() Get module information

One useful function here is server.render(). It replaces placeholders in a template with values from an object. It supports both simple names such as {{name}} and nested paths such as {{user.name}}.

For example:

import server;

define template = "Hello, {{user.name}}!";
define data = {
    user: {
        name: "Developer"
    }
};

print(server.render(template, data));
Enter fullscreen mode Exit fullscreen mode

The result is:

Hello, Developer!
Enter fullscreen mode Exit fullscreen mode

Configuring the server

The server is started with server.serve():

server.serve(root, port, options);
Enter fullscreen mode Exit fullscreen mode

The root directory is used for static files, templates, and file responses. The default port is 8080.

The current implementation accepts these configuration options:

Option Purpose
host Listening IPv4 address; defaults to 0.0.0.0
static Enable or disable static file serving
index Default index filename; defaults to index.html
notFound Custom text for missing routes
workers Number of prefork worker processes
max_requests Maximum total requests before the server stops; 0 means unlimited
max_connections_per_worker Maximum connections handled by each worker
request_timeout Socket request timeout in seconds
max_keep_alive_requests Maximum requests per persistent connection
backlog Listening socket backlog
reuse_port Enable SO_REUSEPORT
cors Enable the built-in CORS headers
headers Object containing global response headers
security Enable built-in security headers
protocol Set to "https" or "tls" to enable TLS
cert TLS certificate file
key TLS private key file

Here's an example configuration:

server.serve(".", 8080, {
    host: "0.0.0.0",
    static: true,
    index: "index.html",
    workers: 4,
    request_timeout: 15,
    max_keep_alive_requests: 100,
    cors: true,
    security: true,
    headers: {
        "X-Powered-By": "greenServeFE"
    }
});
Enter fullscreen mode Exit fullscreen mode

For TLS, both cert and key are required. The implementation uses TLS 1.2 as its minimum protocol version.

There are a few other things worth mentioning. The server supports HTTP/1.1 persistent connections, so multiple requests can use the same connection. It also handles chunked request bodies. For outgoing responses, gzip compression is automatic when the client accepts gzip and the response is large enough.

Putting the APIs together

The examples above show individual features. Here's a larger program that puts several of them into one .gsve file.

It includes middleware, route parameters, query handling, JSON responses, form parsing, cookies, redirects, and multiple HTTP methods.

import server;

func request_info(req, res, next) {
    res.set("X-Powered-By", "greenServeFE");
    next();
}

func home(req, res) {
    res.html("<h1>Welcome to greenServeFE</h1><p>Native HTTP server running.</p>");
}

func health(req, res) {
    res.json({
        status: "ok",
        server: "greenServeFE"
    });
}

func user(req, res) {
    res.json({
        id: req.params.id,
        message: "User information"
    });
}

func search(req, res) {
    res.json({
        term: req.query.term,
        path: req.path
    });
}

func create_user(req, res) {
    res.status(201);

    res.json({
        message: "User created",
        name: req.form.name,
        email: req.form.email
    });
}

func update_user(req, res) {
    res.json({
        message: "User updated",
        id: req.params.id,
        body: req.body
    });
}

func patch_user(req, res) {
    res.json({
        message: "User partially updated",
        id: req.params.id
    });
}

func delete_user(req, res) {
    res.status(200);
    res.json({
        message: "User deleted",
        id: req.params.id
    });
}

func set_session(req, res) {
    res.cookie("session", "greenServeFE", 3600, true);
    res.json({message: "Cookie set"});
}

func get_session(req, res) {
    res.json({
        session: req.cookies.session
    });
}

func clear_session(req, res) {
    res.clearCookie("session");
    res.json({message: "Cookie cleared"});
}

func redirect_home(req, res) {
    res.redirect("/");
}

func not_found(req, res) {
    res.status(404);
    res.json({error: "Route not found"});
}

server.use("/", request_info);

server.get("/", home);
server.get("/health", health);
server.get("/users/:id", user);
server.get("/search", search);

server.post("/users", create_user);
server.put("/users/:id", update_user);
server.patch("/users/:id", patch_user);
server.delete("/users/:id", delete_user);

server.get("/session/set", set_session);
server.get("/session", get_session);
server.get("/session/clear", clear_session);

server.get("/redirect", redirect_home);
server.any("/missing", not_found);

print("greenServeFE server listening on port 8080");

server.serve(".", 8080, {
    host: "0.0.0.0",
    static: false,
    workers: 4,
    request_timeout: 15,
    max_keep_alive_requests: 100,
    cors: true,
    security: true,
    headers: {
        "X-Application": "greenServeFE"
    }
});
Enter fullscreen mode Exit fullscreen mode

Everything is kept in one file here to make it easier to follow. In a larger application, the handlers could be separated into different files or supported by other native modules.

Some things I find interesting about this implementation

A few parts of the server module stand out to me.

  • It's a native C module. HTTP functionality is available to greenServeFE programs without adding new language keywords.
  • The routing and middleware system gives programs a way to organize request handling and share logic between routes.
  • The worker pool uses separate processes. The server uses a prefork model and distributes accepted connections through the listening socket.
  • Persistent connections allow multiple requests to use the same HTTP connection.
  • TLS and gzip compression are handled by the server implementation.
  • The HTTP client is part of the same module. A program can handle incoming requests and make outgoing HTTP requests using one module.

There are still things I'd like to improve, especially around testing, documentation, and adding more examples. This is the current API, not necessarily the final design.

Contributions and feedback

I'm developing greenServeFE as an open-source project, and I'd like other developers to have a look at it.

The public repository contains the core language implementation, including the lexer, parser, compiler, bytecode system, VM, runtime values, and native module interface.

Top comments (0)