Wisp is in pre-release, self-hosted since GitHub suspended us. Install it, or see the changelog.

Wisp

Input, Output and Errors

Input

Each param but cx is read by name: route param, then form field or JSON object member, then query. fn put(id: u64, title: String, done: bool) takes a form post and {"title":"Tea","done":true} alike. A missing param or wrong type is an error naming it.

body: T is the whole JSON body:

SentAnswer
JSON that is a T and passeshandler runs
not JSON400 with where: Invalid JSON: expected `:` at line 1, column 9
JSON not a T, or failing a check422, every problem by field
non-JSON Content-Type, or one that is not UTF-8415
Content-Encoding: gzip (or x-gzip)the server unpacks it first (HTTP/1.1 and HTTP/2)
gzip that is not one gzip file, or ends too soon400
gzip with more than one dynamic block for each 24 bytes of its deflate data (not the gzip header and trailer), and 64 more400
unpacked size over the body limit413
other Content-Encoding (br, zstd, deflate), a list of codings, a repeated header415
no body, body: Option<T>None

An unpacked request has no content-encoding and no content-length header. A route with an Upload holds a packed body in memory, within its limit, and does not stream it to disk. The early RATE_LIMIT and SIGNED_IN check of an upload does not run for a packed body, over HTTP/1.1 and HTTP/2: the server reads and unpacks it first. The edge build does not unpack. See Runtime.

FromJson

#[derive(FromJson)] reads a struct from an object.

  • Option can be absent or null. An absent bool is false. Extra members are ignored.
  • A one-field tuple struct reads as that field. A fieldless enum reads from its variant name ("Low").
  • Also implemented for strings, numbers (300 is not a u8), bool, Option, Vec, Box, string-key maps and wisp::Value (any JSON: body.get("title")).
  • wisp::from_json::<T>(bytes) reads JSON anywhere. wisp::json::parse gives a Value: get as_str as_bool as_i64 as_f64 as_number as_array as_object (and as_array_mut as_object_mut into_array into_object to change or take it), or match v.kind() on wisp::json::Kind. Make one with Value::from(..), Value::number("1e3") or Value::NULL.

Checks

RuleChecksOn
len = 1..=200length or item countstrings, lists
min = 0 max = 100boundsnumbers
min_len = 1 max_len = 200length or itemsstrings, lists
emailwhat <input type="email"> takes, 254 bytes at most, with no control, white space or invisible mark in the domainstrings
  • min and max compare integers exactly, a u128 above i128::MAX too.
  • Past ASCII, email refuses a control and white space in the domain. It also refuses each Default_Ignorable_Code_Point of Unicode 18.0.0 except the joiners U+200C and U+200D. These are U+00AD, U+034F, U+061C, U+115F, U+1160, U+17B4, U+17B5 and U+180B to U+180F. Then U+200B, U+200E, U+200F, U+202A to U+202E, U+2060 to U+206F and U+3164. Then U+FE00 to U+FE0F, U+FEFF, U+FFA0 and U+FFF0 to U+FFF8. Last, U+1BCA0 to U+1BCA3, U+1D173 to U+1D17A and U+E0000 to U+E0FFF. IDNA2008 disallows each of them or leaves it unassigned, so a real name past ASCII still passes.
  • None passes. Further rules (url slug uuid alnum phone not_blank ascii lowercase no_html date min_date max_date step one_of pattern with): Data, files and jobs.
  • An unknown rule is a build error listing the valid ones.
  • A len range that no length fits (..0, 5..3, 3..=2) fails the build: `len = ..0` holds no length: write a range such as `len = 1..=100`.
  • Own checks: return invalid("email", "is already taken") (422). Error::invalid(..).and(..) names several fields.

Output

ReturnsClient gets
a Json value (#[derive(Json)], Vec, numbers, strings, maps)200 + JSON
nothing, Result<()>204
a Response with status 205bodiless
Responseit
Option<Response>it, or 404
Option<T>JSON, 204 for Some(()), 404 for None
any of these in a Resultsame, or the error

Response::created(&v) is 201. Response::json_of(&v).with_status(202) sets 202. .with_header(name, value) adds a header (also on Error, and cx.set_header in a page). Its value is a String or a &'static str. A &'static str is not copied. A borrowed &str that is not 'static needs .to_string(). A single-valued header (content-type, cache-control, location, etag) replaces the earlier value. content-length and transfer-encoding belong to the server. An answer to HEAD keeps your content-length, but not for a 204 or a 304, and a 205 says content-length: 0. Response::text and its kin take a String or &str (the IntoText trait). Response::text sends content-type: text/plain;charset=UTF-8 on every target. At load, the edge bridge checks if new Response(string) has this type (Deno does, Bun does not). Where it does, the bridge sends a plain text 200 with no headers object. In a page, cx.set_status(404) sets the status; one outside 200 to 599 is logged and ignored.

Query: cx.query("q"), cx.query_or("page", 1) (parsed, else the default), cx.query_string() (raw, no ?). cx.request_id() is sent back as x-request-id.

Errors Are JSON

An error is JSON (else the app's +error.wisp, else Wisp's default page) when the request targets a +server.rs, is under /api, sent JSON or prefers JSON by Accept (media types in any case), or has no Accept and is not a browser navigating. An app with no pages always answers JSON.

{"status": 422, "code": "invalid", "error": "title: must have at least 1 character",
 "errors": {"title": "must have at least 1 character"}}
  • errors only for invalid input.
  • code: the status's (bad_request unauthorized forbidden not_found method_not_allowed conflict precondition_failed too_large unsupported_media_type invalid rate_limited internal unavailable) or your own: Error::new(409, "That email is taken").with_code("email_taken").
  • error is your message, else the status name.
  • accept: application/problem+json, or WISP_PROBLEM_JSON=on, gives RFC 9457 (type, title, status, code, detail, errors).
  • This covers 404, 405, error(403, "…") and panics (500, details in dev only).

Webhooks

// src/routes/hooks/github/+server.rs
fn post(cx: &mut Cx, body: Value) -> Result {
    cx.need_signature("GITHUB_SECRET", "x-hub-signature-256")?; // 401 unless it matches
    Ok(())
}
  • HMAC-SHA256 of the body with the secret in that variable, hex (with or without sha256=) or base64 (Shopify).
  • Stripe's stripe-signature (t=…,v1=…) signs the time too, and is refused after five minutes.
  • Other schemes: wisp::hex(&wisp::hmac_sha256(secret, message)), wisp::secure_eq.

Big Lists

fn get() -> Response {
    Response::ndjson(|out| async move {
        for page in 0.. {
            let rows = db::page(page).await;
            if rows.is_empty() {
                break;
            }
            // stops once the client left
            for row in rows {
                out.line(&row).await?;
            }
        }
        Ok(())
    })
}

Versions, CORS

  • Versions are folders (api/v1/notes), or cx.header_or("x-api-version", 1). (group) folders do not change URLs. [id=int] answers /api/notes/abc with 404 before any code runs.
  • cx.cors("*")? in before (a preflight is the Err it returns), or const CORS: &str = "*";, where the route answers its own preflight with 204 before its MIDDLEWARE or rate limit. Errors keep the CORS headers, so the page can read them. A request with no origin gets vary: origin from a list (or access-control-allow-origin: * from *), so a shared cache never hands it to another site's request. On a CACHE route, the kept answer holds each header that the handler set, also those before cx.cors. With cx.cors("*"), a request with any origin gets a hit. When access-control-allow-origin echoes an origin, the kept answer holds one origin at a time. A request with the same origin gets a hit, and alternating origins run the handler again.
  • Allowed sites: "https://app.example.com https://example.com" (these can then send cookies). Others get no CORS headers.
  • Some paths only: if cx.path().starts_with("/api/") { cx.cors("*")?; }, or a cors rule in [package.metadata.wisp]: cors = ["/api/[...p] https://app.example.com https://x.com", "/pub/[...p] *"] (pattern origins, the first rule that fits the path wins). It adds the same headers as cx.cors to every reply of those paths and answers their preflight with a 204 whatever the route says (a 405, a 404, an allow list), so no route needs const CORS. The 204 keeps the headers of the before hook, the server and the headers rules (a content-security-policy too). It drops only the headers of the answer that it replaces: allow, location, retry-after, www-authenticate, content-type, content-encoding, content-language, content-length, content-location, content-range, content-disposition, etag and last-modified. No handler runs for an OPTIONS request. A site not listed gets vary: origin and no allowance. A static export (wisp build --static) writes no CORS headers: that is for the server. A route's own cx.cors or const CORS wins: a reply that already has access-control-allow-origin or vary: origin is left as the route made it. Rules cover reads and preflights. The origin check of a credentialed write (CSRF) does not change, so for those use the route's const CORS. On the edge, each request for a path with a cors rule goes to the app. The bridge keeps no answer of it for the next request. An app with no cors rule pays nothing for it.
  • cx.route() is the pattern (/api/posts/[id]), a label for metrics that does not grow with every id.

Is This Page Useful?

View This Page's Source

Type to search every docs page and heading.