A small introduction to web services with Rust and Rocket. It demonstrates routes, query parameters, JSON responses, cookies, static files, and local request testing.
The service estimates π by sampling random points in a unit square. Approximately
π/4 of them fall inside a quarter circle, so the estimate is 4 * inside / total.
Install stable Rust, then run from the repository root so Rocket can find static/:
cargo run --lockedOpen http://127.0.0.1:8000/ to use the form. The sample count is prefilled from
the browser's saved n cookie when valid; otherwise it starts blank and uses the
server default. Save default stores the entered count for this browser.
Clear default removes the cookie and empties the field. The result also shows
the number of samples used.
For a smaller live-coding app, run cargo run --locked --example minimal from
the repository root. examples/minimal.rs serves
minimal_static/index.html: one route, a required
sample count, a range check, and a plain HTML form that opens the JSON response.
It uses no JavaScript or cookies. Both apps use port 8000; run one at a time.
| Request | Behavior |
|---|---|
GET /pi/monte_carlo?n=1000 |
Return JSON with inside, total, and pi. |
POST /pi/defaults?n=50000 |
Save the sample count in a cookie. |
POST /pi/defaults |
Clear the saved default. |
Sample counts must be integers from 1 to 1,000,000. Invalid counts return HTTP 400 Bad Request; an invalid POST leaves the saved default unchanged.
An explicit count overrides the saved default. An omitted or empty n uses the
saved default, or 100,000 when none is available. On /pi/defaults, an omitted
or empty n clears the cookie. Invalid saved cookies are ignored.
Try a request:
curl 'http://127.0.0.1:8000/pi/monte_carlo?n=1000'To demonstrate cookies, use the same cookie file for subsequent requests:
# Save a default.
curl -c /tmp/cloud-pi-cookies.txt -X POST 'http://127.0.0.1:8000/pi/defaults?n=50000'
# Use it, then override it for one request.
curl -b /tmp/cloud-pi-cookies.txt 'http://127.0.0.1:8000/pi/monte_carlo'
curl -b /tmp/cloud-pi-cookies.txt 'http://127.0.0.1:8000/pi/monte_carlo?n=1000'
# Clear the saved default and update the cookie file.
curl -b /tmp/cloud-pi-cookies.txt -c /tmp/cloud-pi-cookies.txt -X POST 'http://127.0.0.1:8000/pi/defaults'
# See a validation error, including its HTTP status.
curl -i 'http://127.0.0.1:8000/pi/monte_carlo?n=0'cargo test --lockedTests cover the result formula, sample limits, defaults, explicit overrides, malformed input, and invalid cookies. They use Rocket's local client without starting a network listener.