Match Tuple Guards Route Dispatch

Dispatch routes by matching a method and path tuple, with a guard narrowing the id prefix and a wildcard arm rejecting verbs the router does not accept.

RustCli Tooling

Code

rustsnippet
26 lines
fn dispatch(method: &str, path: &str) -> String {
    // tuple pattern matches both segments at once; a guard narrows the prefix
    match (method, path) {
        ("GET", "/health") => "200 ok".to_string(),
        ("GET", p) if p.starts_with("/users/") => {
            let id = p.trim_start_matches("/users/");
            format!("200 user {id}")
        }
        ("POST", "/users") => "201 created".to_string(),
        ("GET", _) => "404 not found".to_string(),
        _ => format!("405 method {method} not allowed"),
    }
}

fn main() {
    let routes = [
        ("GET", "/health"),
        ("GET", "/users/42"),
        ("POST", "/users"),
        ("GET", "/metrics"),
        ("DELETE", "/users/42"),
    ];
    for (method, path) in routes {
        println!("{method} {path} -> {}", dispatch(method, path));
    }
}

Match Tuple Guards Route Dispatch: reading the source

The edit surface comes down to dispatch and main — the remainder is wiring.

One loop does the cycling here: for (method, path) in routes. A match spells out every case; omit one and the code does not compile.

Caveats

  • Nothing depends on a registry or lockfile — it is dependency-free by design.

Using it

Entry signature: fn dispatch(method: &str, path: &str) -> String

Execute the file and main walks through dispatch, in that order.

Key statements

("GET", p) if p.starts_with("/users/") => {
    let id = p.trim_start_matches("/users/");
    format!("200 user {id}")
}

Interactive Tools for This Topic

FAQ

How do you run Match Tuple Guards Route Dispatch?
Execute it straight away — the program needs nothing beyond the runtime.