gdDocumentation0.8.0

Serve HTML and a JSON API

English | 日本語

Build one service with two routes: / renders a greeting from an HTML template, and /api/hello returns JSON. Keep the template and the script together in the same directory.

Write the template

Save index.html:

<!doctype html>
<html lang="en">
<title>Hello</title>
<h1>Hello, {{name}}!</h1>
<p>Rendered by a template.</p>
</html>

{{name}} inserts a value with context-aware escaping. Do not use the raw {{{...}}} form for untrusted input.

Add the routes

Save app.gd:

var app := GD.web.app()

# Render the greeting and forward rendering failures.
func page(_req: GDWebRequest) -> GDWebResponse, Err:
    return GD.web.view("index.html", {"name": "world"})

# Encode the greeting and forward encoding failures.
func hello(_req: GDWebRequest) -> GDWebResponse, Err:
    return GD.web.json({"message": "Hello, world!"})

func main():
    app.route("GET", "/", page)
    app.route("GET", "/api/hello", hello)
    app.listen(8080, "127.0.0.1")!
    return 0
gd serve app.gd
curl http://127.0.0.1:8080/
curl http://127.0.0.1:8080/api/hello

Open the first URL in a browser to see the rendered greeting. The second route returns an object with a message field. The bind address accepts connections only from the local machine.

Keep errors intact

GD.web.view can fail while reading or rendering the template. GD.web.json can fail while encoding a value. Returning their result directly preserves the Err and lets GDWebApp.on_error handle it at the application boundary.

Do not write return reply, null after discarding a failed result. Helpers that already return a response and Err can be returned directly. GD.web.html instead accepts already-rendered HTML and has no separate error slot.

Read request data

A request handler receives GDWebRequest. For a JSON body, check the decoding error before accessing any fields:

func echo(req: GDWebRequest) -> GDWebResponse, Err:
    var data, err := req.json()
    if err != null:
        return null, err
    return GD.web.json(data)

Register this as a POST route with app.route("POST", "/api/echo", echo). A body read consumes input; for large uploads use read or save instead of collecting the whole body.

Reuse a template

When rendering the same template repeatedly, GD.html.template creates a reusable GDHTMLTemplate. Keep the parsed object and call execute for each data dictionary. Treat parsing and rendering as separate error boundaries.