Black Pine

Tiny web server (zero dependencies)

A lightweight HTTP server built with Java's built-in 'HttpServer'

How It Works

The web server uses Java’s com.sun.net.httpserver.HttpServer to create a lightweight HTTP server that:

  1. Listens on a specified port (default: 9999)
  2. Maps URL paths to JSON response files stored in the responses/ directory
  3. Serves the file contents as the JSON response body with a custom HTTP status

How To Create A Web Server

Project Structure

responses
    users.json
    user.json
    user_not_found.json
src
    WebServer.java

Code Snippets

WebServer.java:

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;

void main() throws Exception {
    var server = HttpServer.create(new InetSocketAddress(9999), 0);
    server.createContext("/api/rest/v1/users/12345",
                     exchange -> readFromFile(exchange, "responses/user.json", 200));
    server.createContext("/api/rest/v1/users/54321",
                     exchange -> readFromFile(exchange, "responses/user_not_found.json", 404));
    server.start();
    IO.println("Serving on http://localhost:9999/api/rest/v1/users/12345");
    IO.println("Serving on http://localhost:9999/api/rest/v1/users/54321");
}

private static void readFromFile(HttpExchange exchange, String path,
                                 int responseStatus) throws IOException {
    byte[] body = Files.readAllBytes(Path.of(path));
    exchange.getResponseHeaders().add("Content-Type", "application/json; charset=utf-8");
    exchange.sendResponseHeaders(responseStatus, body.length);
    try (OutputStream os = exchange.getResponseBody()) {
        os.write(body);
    }
    exchange.close();
}

Adding New Endpoints

To add a new endpoint:

  1. Create a JSON response body file in the responses/ directory:

    {
      "users": [
        {"id": 1, "name": "John Doe"},
        {"id": 2, "name": "Jane Smith"}
      ]
    }
  2. Add the endpoint mapping in WebServer.java:

    server.createContext("/api/rest/v2/users/all",
        exchange -> readFromFile(exchange, "responses/users.json"));
  3. Add a console log (optional but recommended):

    IO.println("Serving web server on http://localhost:9999/api/users");
  4. Restart the server