# Getting started
## Install
```toml
[dependencies]
joist = "0.1"
```
Joist needs Rust 1.74 or newer, and pulls in nothing else.
## The smallest service
```rust
use joist::{Response, Router, Server};
fn main() {
let mut router = Router::new();
router.get("/", |_| Response::text("it works"));
let server = Server::new(router).bind("127.0.0.1:8080").unwrap();
println!("listening on http://{}", server.addr());
server.wait();
}
```
`bind` returns as soon as the listener is up, and the server runs on its own
thread. `wait` blocks for the life of the process. Bind to port `0` and the OS
picks a free port, which `addr()` then reports. That is how the test suite runs
without arguing over ports.
## Reading the request
```rust
let verbose = req.query_param("verbose").is_some();
Response::text(format!("user {id}, verbose {verbose}"))
});
```
`param` reads a path segment captured by the route. `query_param` reads the
query string and decodes percent escapes and `+`. Both give you `None` rather
than an empty string when something is missing, so you can tell "absent" from
"present and blank".
## JSON
```rust
use joist::{Json, Response, Status};
Ok(value) => value,
Err(err) => return Response::error(Status::BAD_REQUEST, &err.to_string()),
};
let name = match body.get("name").and_then(Json::as_str) {
Some(name) => name,
None => return Response::error(Status::UNPROCESSABLE_ENTITY, "name is required"),
};
Response::json(&Json::object(vec![
("created", Json::from(true)),
("name", Json::from(name)),
]))
.with_status(Status::CREATED)
});
```
`Response::error` builds a JSON body of `{"error": ..., "status": ...}` with the
message run through the encoder, so a quote or newline in it cannot break the
payload.
Numbers are `Json::Int(i64)` or `Json::Float(f64)`, not one `f64`. An integer id
keeps every digit rather than being rounded above 2^53, and a whole-number float
serialises as `1.0` so it does not read back as an integer. `as_i64` answers for
either when the value is exactly an integer an `i64` can hold. `Json` is
`#[non_exhaustive]`, so matching on it directly needs a `_` arm; the `as_*`
accessors avoid the question.
## Reading and writing bodies
A body is reached through an accessor, not a field:
```rust
Response::text(format!("{} bytes", bytes.len()))
});
```
`Body` is opaque so it can become a file or a stream later without changing the
type of every request and response that carries one. `len()` and `as_bytes()`
return `Option` for the same reason: a stream will not be able to answer them.
Every body this version can build does, so `unwrap` on them is safe today.
`req.body_str()` and `req.json()` are usually what you want and are unchanged.
## Testing a handler
A handler is an ordinary function, so a test can call one directly. Build the
request it should receive:
```rust
use joist::{Json, Method, Request, Response, Status};
fn show_user(req: &Request) -> Response {
match req.param("id") {
Some(id) => Response::json(&Json::object(vec![("id", Json::from(id))])),
None => Response::error(Status::BAD_REQUEST, "no id"),
}
}
#[test]
fn returns_the_requested_user() {
let req = Request::new(Method::Get, "/users/42").with_param("id", "42");
let res = show_user(&req);
assert_eq!(res.status, Status::OK);
assert_eq!(res.body().as_bytes(), Some(&br#"{"id":"42"}"#[..]));
}
```
`Request::new` splits the target into a path and a query and percent-decodes the
path, exactly as the parser does. `with_header`, `with_body`, `with_param`,
`with_version` and `with_peer` fill in the rest. No listener, no socket, no
`Server`.
## Middleware
```rust
use joist::{Middleware, Request, RequestLog, Response, Status};
struct RequireToken;
impl Middleware for RequireToken {
fn before(&self, req: &mut Request) -> Option<Response> {
match req.headers.get("Authorization") {
Some(_) => None,
None => Some(Response::error(Status::UNAUTHORIZED, "missing token")),
}
}
}
let server = Server::new(router)
.with(RequestLog)
.with(RequireToken)
.bind("127.0.0.1:8080")?;
```
Returning `Some` from `before` skips the handler. `after` hooks still run, so
`RequestLog` records the rejected request too. See
[middleware.md](middleware.md).
## Configuration
```rust
use joist::Config;
let mut config = Config::from_file("app.conf")?; // defaults
config.merge(Config::from_env("APP_")); // overrides win
let port = config.int("port").unwrap_or(8080);
```
Keys normalise to lowercase with `_` becoming `.`, so `APP_DATABASE_URL` from
the environment and `database.url` from a file are the same setting.
## Plugins
A plugin bundles routes so they can be reused across services.
```rust
use joist::{Config, Json, Plugin, Response, Router};
struct Health;
impl Plugin for Health {
fn name(&self) -> &'static str { "health" }
fn install(self: Box<Self>, router: &mut Router, config: &Config) {
let service = config.get_or("service.name", "unknown").to_string();
router.get("/healthz", move |_| {
Response::json(&Json::object(vec![("service", Json::from(service.clone()))]))
});
}
}
let server = Server::new(router).config(config).plugin(Health).bind(addr)?;
```
## Shutting down
```rust
let server = Server::new(router).bind("127.0.0.1:8080")?;
let stop = server.shutdown_handle();
// From a signal handler, another thread, an admin route:
stop.stop();
server.wait(); // returns once in-flight requests finish
```
## Tuning
| `workers(n)` | 4 per core, clamped to 4-256 | Lower for a memory-constrained box, higher for handlers that block on slow I/O |
| `max_body_bytes(n)` | 2 MB | Raise for uploads, lower for a JSON-only API |
| `read_timeout(t)` | 30s | Bounds one read or write, which is what drops a silent connection. `None` waits forever |
| `request_timeout(t)` | 30s | A deadline over one request and its response. Raise it for large uploads or downloads over slow links |
## Running the example
```sh
cargo run --example hello
curl localhost:8080/hello/martin
curl -X POST localhost:8080/echo -d '{"a":1}'
curl localhost:8080/healthz
```