soma.cell

Redirects

redirect() sends an HTTP redirect response to the browser. Serve: soma serve 057_redirect.cell Test: curl localhost:8080/old-page -> redirects to /

Example 057 of the basic Soma programs: a small, commented program that teaches one thing. Every output below was printed by soma 3.2.4 when this page was built.

How it is built

The cell RedirectDemo declares 3 signals in its face: request(method: String, path: String, body: String) -> String, add(name: String) -> String and demo() -> String; keeps 1 memory slot: items (Map<String, String>, persistent and consistent). Handlers: request (line 25), add (line 30) and demo (line 37).

Generated from soma describe on this file.

The source

057_redirect.cell

// ============================================================================
// 057 — Redirects
// ============================================================================
// redirect() sends an HTTP redirect response to the browser.
//
// Serve: soma serve 057_redirect.cell
// Test:  curl localhost:8080/old-page -> redirects to /
//
// Run:   soma run 057_redirect.cell demo
// Expect:
//   Added item, redirecting...
//   done

cell RedirectDemo {
    face {
        signal request(method: String, path: String, body: String) -> String
        signal add(name: String) -> String
        signal demo() -> String
    }

    memory {
        items: Map<String, String> [persistent, consistent]
    }

    on request(method: String, path: String, body: String) {
        return html("<h1>Home Page</h1><p>Add an item: <a href='/add?name=test'>Add Test</a></p>")
    }

    // After adding, redirect back to home page
    on add(name: String) {
        let id = to_string(next_id())
        items.set(id, name)
        // redirect() sends a 302 redirect
        return redirect("/")
    }

    on demo() {
        let id = to_string(next_id())
        items.set(id, "test-item")
        print("Added item, redirecting...")
        return "done"
    }
}

What the toolchain says

$ soma check 057_redirect.cell
✓ All checks passed.
$ soma run 057_redirect.cell demo
Added item, redirecting...
done