The basics
Routes and controllers
use smeltery::prelude::*;
async fn home() -> Html<&'static str> {
Html("<h1>Welcome</h1>")
}
async fn show(Path(id): Path<u64>) -> Result<String> {
if id == 0 {
return Err(Error::not_found());
}
Ok(format!("post {id}"))
}
async fn index() -> &'static str { "all posts" }
async fn dashboard() -> &'static str { "admin" }
pub fn routes(r: &mut Router) {
r.get("/", home).name("home");
r.resource("/posts").index(index).show(show);
r.group("/admin", |r| {
r.get("/", dashboard).name("dashboard");
})
.name("admin.")
.middleware("auth");
}
get,post,put,patch,delete,any;.name("…");.middleware("alias").- Paths use
{param}placeholders and{*rest}for a catch-all tail. group(prefix, …)with.name("prefix.")and.middleware("alias")for every route in it.resource("/posts")declares the actions you pick:
| Action | Method | Path | Name |
|---|---|---|---|
index |
GET | /posts |
posts.index |
create |
GET | /posts/create |
posts.create |
store |
POST | /posts |
posts.store |
show |
GET | /posts/{post} |
posts.show |
edit |
GET | /posts/{post}/edit |
posts.edit |
update |
PUT, PATCH | /posts/{post} |
posts.update |
destroy |
DELETE | /posts/{post} |
posts.destroy |
app.url("posts.show", &[("post", "7")])builds/posts/7; extra parameters become the query string.- HTML forms send
PUT,PATCHandDELETEas aPOSTwith a_methodfield (or theX-HTTP-Method-Overrideheader). - Routes from
routes/api.rsare registered withapi_routesand live under/api. - Files in
public/are served as-is when no route matches, withETag,Last-Modifiedand theCache-ControlofSTATIC_CACHE_CONTROL(defaultno-cache: browsers revalidate and get a 304 while the file is unchanged). Apps whose asset URLs change with their content can setpublic, max-age=31536000, immutable. - Files under
/storage(uploads, aftersmeltery storage:link) also getContent-Security-Policy: sandbox, so a stored HTML or SVG file never runs as a page of the site,X-Content-Type-Options: nosniff, andContent-Disposition: attachmentunless they are a PNG, JPEG, GIF, WebP, AVIF, BMP or icon image, a PDF, plain text, video or audio. PDFs get nosandbox(browsers do not show a sandboxed PDF). The headers follow the file that is served: any file frompublic/whose real path (links followed) lies instorage/app/publicorpublic/storagegets them, whatever URL reached it. A static-file path with a segment that ends in.or a space, or holds:or\(/storage./…,/storage%2e/…,/storage::$INDEX_ALLOCATION/…), answers 404 on every OS, because Windows opens such names as another file. - The framework adds
GET /up, a health check for load balancers and uptime monitors:200with the textOKandCache-Control: no-store, without a session or CSRF check.route:listshows it. An app route atGET /upreplaces it;AppBuilder::without_health_route()leaves it out. .middleware("throttle:5,1")allows a route 5 requests a minute per client (throttle:<max>,<minutes>;throttle:<max>counts per minute). The client is the authenticated user (the request's principal: a signed-in session on web routes, or the principal anauth:alias listed beforethrottle:stored, see Guards and the principal), else the address afterTRUSTED_PROXIES(an IPv6 client by its /64). Each route counts on its own, by its path pattern, so/reset-password/{token}has one counter for every token. The count lives in the app's cache store (CACHE_STORE), so the processes of an app (serve --no-agentsbesidework, several web processes) share it on thedatabase,redis,memcachedandfilestores; withCACHE_STORE=nullit lives in the process's memory. A cache error answers 500 rather than letting the request through. Responses carryX-RateLimit-LimitandX-RateLimit-Remaining. Past the limit a form on a web route is sent back (303, its input flashed) with "Too many attempts. Please try again in N seconds." on the fieldemail(throttle:5,1,nameputs it onname), and JSON clients and API routes get 429 "Too Many Requests" withRetry-After. An invalid value (throttle:0,throttle:x) stops the app at boot. The windows are fixed and follow the clock (throttle:5,1counts per calendar minute): a client that sends 5 requests at the end of one minute and 5 at the start of the next gets all 10 through within a few seconds.- Aliases with arguments (
throttle:5,1,auth:web) come from middleware families: a prefix and a function that builds the middleware for each route from the arguments and the route (POST /login), while the app builds. An error from it stops the app at boot. Core has the familiesthrottleandauth;AppBuilder::middleware_familyadds others:
use smeltery::middleware::{BoxedMiddleware, Next, Request};
use smeltery::{AppBuilder, Error};
fn build(app: AppBuilder) -> AppBuilder {
// `.middleware("tag:beta")` adds `X-Tag: beta` to the route's responses.
app.middleware_family("tag", |args, _route| {
let value = smeltery::http::HeaderValue::from_str(args)
.map_err(|_| Error::internal(format!("invalid tag `{args}`")))?;
Ok(BoxedMiddleware::new(move |req: Request, next: Next| {
let value = value.clone();
async move {
let mut res = next.run(req).await;
res.headers_mut().insert("x-tag", value);
res
}
}))
})
}
Two families with one prefix, a prefix that is empty or holds :, and a plain alias that starts with a family's
<prefix>: stop the app at boot. route:list shows the alias as written.
Handlers are async functions. Their arguments are extractors: Path, Query, Form, Json (Axum's, re-exported in
smeltery::http), App, ClientInfo (the client's IP, scheme and host, see The server), and
Config<T> for your config structs. They return anything that implements
IntoResponse, usually smeltery::Result<T>, or a Mold template struct (below).
smeltery::http::wants_json(&headers) tells whether a client asks for JSON (its Accept names application/json or
a +json type: error pages, auth and verified answer JSON then) and smeltery::http::is_inertia(&headers)
whether a request is an Inertia visit (X-Inertia: true).