日本語

Routes

A route is a page the server renders at a typed path. This page covers declaring one in routes!, the types a path parameter can hold, and the handler that serves it.

Declaring a route

A Route<P = (), Q = ()> is a page served at a path whose parameters are P, with search parameters Q. You declare it as a constant in routes!, on a line that names the handler serving it: const MEMBER: Route<i32> = "/members/{id}" => member;. A route without a handler cannot be declared.

The first line of the block, such as fn pages(Router<()>);, names the function the macro writes and the router state its handlers take. That function takes a Router<State> and returns it with every route of the block registered on GET. routes! needs the axum feature, which is on by default.

Path parameters

A parameter is a whole segment written {name}, as in axum. P is () for a path without one, one Segment type for one, and a tuple of two to six for more, in path order. The name inside the braces is for the reader and for axum. The position decides which value fills it.

The macro counts the segments, so a path whose count differs from P fails to compile:

use hypersig::Route;

hypersig::routes! {
    fn pages(Router<()>);
    // error[E0080]: evaluation panicked: the route's `{name}` segments differ
    // in number from the values of its parameter type
    const MEMBER: Route<i32> = "/members" => member;
}

What a segment can hold

TypeThe segment holdsA request gets a 404 for
i32, i64, u32, u64The number's digitsText that does not parse into the type
PathSegmentAny text, percent-encodedA segment that decodes to empty, ., or ..
An enum with #[derive(Segment)]The string serde writes for the variantText that names no variant
Rest, from a last segment {*name}The rest of the path, /s includedA part that decodes to . or ..
use hypersig::{PathSegment, Rest, Route, Segment, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Team {}

// Each variant is one segment, spelled as serde writes the variant.
#[derive(Segment, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
enum Tab {
    Overview,
    TeamSettings,
}

hypersig::routes! {
    fn pages(Router<()>);
    const TAB: Route<(PathSegment, Tab)> = "/teams/{team}/{tab}" => tab;
    const FILE: Route<Rest> = "/files/{*path}" => file;
}

// In a `const`, an empty segment, `.`, or `..` fails to compile.
const RED: PathSegment = PathSegment::new("red team");
assert_eq!(TAB.url((RED, Tab::TeamSettings)).as_str(), "/teams/red%20team/team-settings");

// Text read at run time, such as a name from a database, goes through `parse`.
assert!(PathSegment::parse("..").is_err());
let blue = PathSegment::parse("blue").expect("a segment");
assert_eq!(TAB.url((blue, Tab::Overview)).as_str(), "/teams/blue/overview");

// A `Rest` keeps its `/`s and percent-encodes each part between them.
assert_eq!(FILE.url(Rest::new("docs/a b.md")).as_str(), "/files/docs/a%20b.md");
assert!(Rest::parse("docs/../../etc").is_err());

Text in a segment

A PathSegment holds any text except an empty string, ., and ... axum does not match a {name} segment against an empty one, so /orgs/ answers 404. The browser removes a . or .. segment from a link before it sends the request, so /orgs/.. opens /, and it reads %2e as . too, so no encoding keeps a dot. A / or a ? in the text is percent-encoded and stays inside the segment.

const fn PathSegment::new(text: &'static str) -> PathSegment takes text written in the program. In a const it refuses those three values at compile time, and outside one it panics. PathSegment::parse(text: impl Into<String>) -> Result<PathSegment, PathSegmentError> reads text built at run time, such as a name from a database. The server refuses the same values in a request, so a handler never receives .. from a client that sent /orgs/%2E%2E by hand. That request gets a 404 before the handler runs.

Enums as segments

#[derive(Segment)] implements Segment for an enum whose variants have no fields. A variant's segment is the string serde writes for it, so a link that reads the enum from a signal and the server write the same URL. The derive follows #[serde(rename_all = "...")] on the enum and #[serde(rename = "...")] on a variant, so rename_all = "kebab-case" turns TeamSettings into /team-settings. It rejects any other serde attribute at compile time, because one could make serde write a variant differently.

The rest of a path

A last segment written {*name}, as in "/files/{*path}", takes the rest of the path, /s included, into a Rest. Only the last value of P can be a Rest. A link percent-encodes each /-separated part and keeps the /s between them. A Rest is not empty and has no part that is . or .., for the reasons a PathSegment gives, and an empty part, as in docs/ or a//b, is kept. Rest::new and Rest::parse check it as PathSegment::new and PathSegment::parse do, and the server refuses the same values in a request, so a handler that opens the file a Rest names never receives ../.

The handler

A page handler is an async fn(State, Args) -> R. State is the router state of the first line, and Args is P, already parsed. It may take one FromRequestParts extractor between the two, as Handler describes. R is a Page<S>, an Option<Page<S>>, or a PageResponse.

  • A path whose segments do not parse into the parameter types gets a 404, and the handler does not run.
  • A handler that returns None gets a 404, as member does in the example below for an id it does not know.
  • Without an else handler on the first line, those 404s have an empty body. Error pages shows how to send a page of your own with them.

What the compiler checks

A parameter type that is not a Segment, such as String, is a compile error. Use PathSegment for text:

use hypersig::Route;

hypersig::routes! {
    fn pages(Router<()>);
    // error[E0277]: `String` cannot be one segment of a URL's path
    const MEMBER: Route<String> = "/members/{name}" => member;
}

routes! also refuses these at compile time:

  • A line without => handler, or a handler whose arguments or answer do not fit its line.
  • A path that does not start with /, or a { or } that does not enclose a whole named segment.
  • A path that holds a byte the browser percent-encodes, such as a space, ?, #, %, or a non-ASCII character, because the request would reach no handler.
  • A {*name} segment that is not last, or whose value is not a Rest.

What routes leave unchecked

  • Nothing checks that the function routes! writes is called, so declare every page of the application in one routes! block and call its one function. A block whose function is never called answers 404 on every page, and rustc reports its handler functions as never used, though not the function itself or a handler written as a closure.
  • An i64 or u64 parameter past 2^53 reaches the handler exactly. A page whose signals hold such a value panics while rendering, because the browser would round it.

A complete example

Two pages: a team at / and a member at /members/{id}. team links to each member from the list item's id, and member answers None, so a 404, for an id it does not know.

src/main.rs
use axum::Router;
use hypersig::html::{a, each, h1, li, p, ul};
use hypersig::{Page, Route, RouterExt, Signals};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize, Clone)]
struct Member {
    id: i32,
    name: String,
}

#[derive(Signals, Serialize, Deserialize)]
struct Team {
    members: Vec<Member>,
}

#[derive(Signals, Serialize, Deserialize)]
struct Profile {
    name: String,
}

hypersig::routes! {
    fn pages(Router<()>);
    const TEAM: Route = "/" => team;
    const MEMBER: Route<i32> = "/members/{id}" => member;
}

fn members() -> Vec<Member> {
    vec![
        Member {
            id: 1,
            name: "Ada".to_owned(),
        },
        Member {
            id: 2,
            name: "Grace".to_owned(),
        },
    ]
}

async fn team((): (), (): ()) -> Page<Team> {
    Page::new("Team", Team { members: members() })
        .child(h1().text("Team"))
        .child(ul().child(each(Team::members(), |member| {
            li().child(
                a().href(MEMBER.link_with(member.at(Member::id())))
                    .bind_text(member.at(Member::name())),
            )
        })))
}

async fn member((): (), id: i32) -> Option<Page<Profile>> {
    let member = members().into_iter().find(|member| member.id == id)?;
    Some(
        Page::new(member.name.clone(), Profile { name: member.name })
            .child(h1().bind_text(Profile::name()))
            .child(p().child(a().href(TEAM.link()).text("Back to the team"))),
    )
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let app = pages(Router::new()).hypersig_runtime();
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
    axum::serve(listener, app).await
}

Next