Local server & routes (API)

TON618 has a built-in HTTP server, no external dependencies (raw sockets).

Simple mode — serve the same content on every request:

ton.serve(8080, "<h1>Hello from TON618!</h1>")

Routing mode — register handlers per path and method, then call serve(port) with no second argument. Every handler takes a single argument, a ton.dict describing the request:

{
    method: "GET",           // the HTTP method
    path: "/user/42",          // the request path, without the query string
    query: {a: "1"},             // parsed query-string parameters, as a dict
    params: {id: "42"},            // ":name" segments captured from the route pattern
    body: ""                         // the raw request body (POST/PUT/... payload)
}

A route's path can contain :name segments, captured into req["params"]:

ton.function userById(req) {
    ton.string id = req["params"]["id"]
    return json({id: id})
}

ton.function search(req) {
    ton.dict query = req["query"]
    ton.string q = has(query, "q") ? query["q"] : ""
    return "You searched for: " + q
}

ton.function createUser(req) {
    print("Received body: " + req["body"])
    return json({ok: true})
}

ton.get("/user/:id", ton.userById)
ton.get("/search", ton.search)          // GET /search?q=kuro -> req["query"]["q"]
ton.post("/users", ton.createUser)

ton.serve(8081)

A handler returning ton.html is served with Content-Type: text/html; anything else is served as text/plain (use json(...) to build a JSON response body, which is still plain text over the wire — set your client to expect application/json if you need that exact header). A path with no matching route or method returns 404. The server is single-threaded and blocking — it handles one request at a time (see Known limitations).

Edit this page on GitHub