Skip to main content

Builder

Struct Builder 

Source
pub struct Builder<G: Gate> { /* private fields */ }
Expand description

Declares an application. Every mistake is reported by build at once, before anything listens.

Implementations§

Source§

impl<G: Gate> Builder<G>

Source

pub fn csrf(self, csrf: Csrf) -> Self

CSRF protection with csrf-sec (re-exported as web_net::csrf_sec), built from a persisted 32-byte key. Required as soon as one route takes an unsafe method and is not exempt.

Source

pub fn redirect_hosts(self, hosts: &[&str]) -> Self

Hosts that Cx::redirect_external may send a visitor to (accounts.example.com). Everything else is refused.

Source

pub fn assets(self, assets: Assets) -> Self

Serves a folder of files under a mount path, before routing and without the gate (files are public).

Source

pub fn health(self, path: &str) -> Self

A liveness path (/healthz): 200 ok whenever the process answers. Answered before routing and without the gate.

Source

pub fn ready( self, path: &str, check: impl Fn() -> bool + Send + Sync + 'static, ) -> Self

A readiness path (/readyz): 200 ready when check says so, 503 not ready otherwise. Keep check to a flag read: it runs on the request path.

Source

pub fn security_headers(self, policy: SecurityHeaders) -> Self

The security headers every reply carries (default SecurityHeaders::default).

Source

pub fn route(self, route: Route<G::Identity, G::Rule>) -> Self

Adds a route.

Examples found in repository?
examples/hello.rs (lines 19-29)
14fn main() -> Result<(), Box<dyn std::error::Error>> {
15    let app = App::builder()
16        .host("127.0.0.1:8091")
17        .development()
18        .base("/app")
19        .route(
20            get("/", |cx| {
21                let users = cx.url("/users/7");
22                cx.html(
23                    200,
24                    &format!("<h1>Hello</h1><a href=\"{users}\">user 7</a>"),
25                );
26                Ok(())
27            })
28            .public(),
29        )
30        .route(
31            get("/users/:id", |cx| {
32                let id: u64 = cx.param_as("id")?;
33                cx.text(200, &format!("user {id}"));
34                Ok(())
35            })
36            .public(),
37        )
38        .route(
39            Route::at("/contact")
40                .get(|cx| {
41                    cx.html(200, "<form method=post><button>Send</button></form>");
42                    Ok(())
43                })
44                .post(|cx| cx.see_other("/"))
45                .public()
46                // A form that changes state gets Builder::csrf(..) and a gate
47                // whose identities carry a CSRF binding instead.
48                .csrf_exempt("demo: the POST changes nothing"),
49        )
50        .build()?;
51
52    let server = serve_net::Server::builder()
53        .listener(serve_net::ListenerSpec::tcp("web", "127.0.0.1:8091"))
54        .serve(app)?;
55    println!("listening on http://127.0.0.1:8091/app/");
56    server.wait();
57    Ok(())
58}
Source

pub fn group(self, group: Group<G::Identity, G::Rule>) -> Self

Adds a group’s routes.

Source

pub fn hook<F>(self, hook: Hook, routes: Routes, f: F) -> Self
where F: Fn(&mut Cx<'_, G::Identity>) -> Result + Send + Sync + 'static,

Runs f at hook for the routes routes selects.

Source

pub fn host(self, host: &str) -> Self

A host the site answers (example.com, or localhost:8080 with its port). The first one is canonical. With no host declared the site answers any host; with hosts declared, any other host gets 421.

Examples found in repository?
examples/hello.rs (line 16)
14fn main() -> Result<(), Box<dyn std::error::Error>> {
15    let app = App::builder()
16        .host("127.0.0.1:8091")
17        .development()
18        .base("/app")
19        .route(
20            get("/", |cx| {
21                let users = cx.url("/users/7");
22                cx.html(
23                    200,
24                    &format!("<h1>Hello</h1><a href=\"{users}\">user 7</a>"),
25                );
26                Ok(())
27            })
28            .public(),
29        )
30        .route(
31            get("/users/:id", |cx| {
32                let id: u64 = cx.param_as("id")?;
33                cx.text(200, &format!("user {id}"));
34                Ok(())
35            })
36            .public(),
37        )
38        .route(
39            Route::at("/contact")
40                .get(|cx| {
41                    cx.html(200, "<form method=post><button>Send</button></form>");
42                    Ok(())
43                })
44                .post(|cx| cx.see_other("/"))
45                .public()
46                // A form that changes state gets Builder::csrf(..) and a gate
47                // whose identities carry a CSRF binding instead.
48                .csrf_exempt("demo: the POST changes nothing"),
49        )
50        .build()?;
51
52    let server = serve_net::Server::builder()
53        .listener(serve_net::ListenerSpec::tcp("web", "127.0.0.1:8091"))
54        .serve(app)?;
55    println!("listening on http://127.0.0.1:8091/app/");
56    server.wait();
57    Ok(())
58}
Source

pub fn alias(self, host: &str) -> Self

A host that is redirected (301, or 308 for unsafe methods) to the canonical host (www.example.com to example.com).

Source

pub fn development(self) -> Self

A development instance: localhost, 127.0.0.1, [::1], and *.localhost are answered as the site (with any port), and HTTPS is not required for them. Never set this in production: it is the only way a Host: localhost is trusted.

Examples found in repository?
examples/hello.rs (line 17)
14fn main() -> Result<(), Box<dyn std::error::Error>> {
15    let app = App::builder()
16        .host("127.0.0.1:8091")
17        .development()
18        .base("/app")
19        .route(
20            get("/", |cx| {
21                let users = cx.url("/users/7");
22                cx.html(
23                    200,
24                    &format!("<h1>Hello</h1><a href=\"{users}\">user 7</a>"),
25                );
26                Ok(())
27            })
28            .public(),
29        )
30        .route(
31            get("/users/:id", |cx| {
32                let id: u64 = cx.param_as("id")?;
33                cx.text(200, &format!("user {id}"));
34                Ok(())
35            })
36            .public(),
37        )
38        .route(
39            Route::at("/contact")
40                .get(|cx| {
41                    cx.html(200, "<form method=post><button>Send</button></form>");
42                    Ok(())
43                })
44                .post(|cx| cx.see_other("/"))
45                .public()
46                // A form that changes state gets Builder::csrf(..) and a gate
47                // whose identities carry a CSRF binding instead.
48                .csrf_exempt("demo: the POST changes nothing"),
49        )
50        .build()?;
51
52    let server = serve_net::Server::builder()
53        .listener(serve_net::ListenerSpec::tcp("web", "127.0.0.1:8091"))
54        .serve(app)?;
55    println!("listening on http://127.0.0.1:8091/app/");
56    server.wait();
57    Ok(())
58}
Source

pub fn base(self, base: &str) -> Self

The path the site is installed under (/blog). It is removed before routing and added back by Cx::url, so routes and links are written as if the site were at /. Requests outside it get 404.

Examples found in repository?
examples/hello.rs (line 18)
14fn main() -> Result<(), Box<dyn std::error::Error>> {
15    let app = App::builder()
16        .host("127.0.0.1:8091")
17        .development()
18        .base("/app")
19        .route(
20            get("/", |cx| {
21                let users = cx.url("/users/7");
22                cx.html(
23                    200,
24                    &format!("<h1>Hello</h1><a href=\"{users}\">user 7</a>"),
25                );
26                Ok(())
27            })
28            .public(),
29        )
30        .route(
31            get("/users/:id", |cx| {
32                let id: u64 = cx.param_as("id")?;
33                cx.text(200, &format!("user {id}"));
34                Ok(())
35            })
36            .public(),
37        )
38        .route(
39            Route::at("/contact")
40                .get(|cx| {
41                    cx.html(200, "<form method=post><button>Send</button></form>");
42                    Ok(())
43                })
44                .post(|cx| cx.see_other("/"))
45                .public()
46                // A form that changes state gets Builder::csrf(..) and a gate
47                // whose identities carry a CSRF binding instead.
48                .csrf_exempt("demo: the POST changes nothing"),
49        )
50        .build()?;
51
52    let server = serve_net::Server::builder()
53        .listener(serve_net::ListenerSpec::tcp("web", "127.0.0.1:8091"))
54        .serve(app)?;
55    println!("listening on http://127.0.0.1:8091/app/");
56    server.wait();
57    Ok(())
58}
Source

pub fn trailing_slash(self, policy: TrailingSlash) -> Self

The trailing-slash policy (default TrailingSlash::Strip).

Source

pub fn lowercase_paths(self) -> Self

Paths are lower case: one with an upper-case letter is redirected.

Source

pub fn https_only(self) -> Self

Plain HTTP is redirected to HTTPS on the canonical host (behind a TLS proxy, serve-net must trust the proxy’s scheme). Needs a host.

Source

pub fn sign_in(self, path: &str) -> Self

The site-relative sign-in page. A Denial::sign_in on a GET or HEAD is then answered with a 303 to it, the page asked for passed as next; without it, or for other methods, the answer is 401.

Source

pub fn challenge(self, challenge: &str) -> Self

The WWW-Authenticate challenge sent with a 401 (default Session).

Source

pub fn render(self, engine: impl Render) -> Self

The template engine.

Source

pub fn events(self, events: impl Events) -> Self

Where refusals, denials, and failures are reported.

Source

pub fn checkpoint(self, checkpoint: impl Checkpoint) -> Self

The in-flight revocation check at web-net’s stages.

Source

pub fn page_limit(self, bytes: usize) -> Self

The budget for one rendered page (default 8 MiB).

Source

pub fn wipe_buffers(self) -> Self

Zero the reply buffers web-net reuses after every request, so one visitor’s page never lingers in memory another request reuses. Costs one pass over the bytes written.

Source

pub fn build(self) -> Result<App<G>, BuildError>

Compiles the application.

§Errors

A BuildError listing every problem: a route without declared access, a malformed pattern, two handlers for one method of one path, an unknown template, a malformed host or base path.

Examples found in repository?
examples/hello.rs (line 50)
14fn main() -> Result<(), Box<dyn std::error::Error>> {
15    let app = App::builder()
16        .host("127.0.0.1:8091")
17        .development()
18        .base("/app")
19        .route(
20            get("/", |cx| {
21                let users = cx.url("/users/7");
22                cx.html(
23                    200,
24                    &format!("<h1>Hello</h1><a href=\"{users}\">user 7</a>"),
25                );
26                Ok(())
27            })
28            .public(),
29        )
30        .route(
31            get("/users/:id", |cx| {
32                let id: u64 = cx.param_as("id")?;
33                cx.text(200, &format!("user {id}"));
34                Ok(())
35            })
36            .public(),
37        )
38        .route(
39            Route::at("/contact")
40                .get(|cx| {
41                    cx.html(200, "<form method=post><button>Send</button></form>");
42                    Ok(())
43                })
44                .post(|cx| cx.see_other("/"))
45                .public()
46                // A form that changes state gets Builder::csrf(..) and a gate
47                // whose identities carry a CSRF binding instead.
48                .csrf_exempt("demo: the POST changes nothing"),
49        )
50        .build()?;
51
52    let server = serve_net::Server::builder()
53        .listener(serve_net::ListenerSpec::tcp("web", "127.0.0.1:8091"))
54        .serve(app)?;
55    println!("listening on http://127.0.0.1:8091/app/");
56    server.wait();
57    Ok(())
58}

Trait Implementations§

Source§

impl<G: Gate> Debug for Builder<G>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<G> !RefUnwindSafe for Builder<G>

§

impl<G> !UnwindSafe for Builder<G>

§

impl<G> Forget for Builder<G>

§

impl<G> Freeze for Builder<G>
where G: Freeze, Vec<Route<<G as Gate>::Identity, <G as Gate>::Rule>>: Freeze, Vec<(Hook, Routes, Arc<dyn Fn(&mut Cx<'_, <G as Gate>::Identity>) -> Result<(), Error> + Send + Sync>)>: Freeze,

§

impl<G> Send for Builder<G>
where Vec<Route<<G as Gate>::Identity, <G as Gate>::Rule>>: Send, Vec<(Hook, Routes, Arc<dyn Fn(&mut Cx<'_, <G as Gate>::Identity>) -> Result<(), Error> + Send + Sync>)>: Send,

§

impl<G> Sync for Builder<G>
where Vec<Route<<G as Gate>::Identity, <G as Gate>::Rule>>: Sync, Vec<(Hook, Routes, Arc<dyn Fn(&mut Cx<'_, <G as Gate>::Identity>) -> Result<(), Error> + Send + Sync>)>: Sync,

§

impl<G> Unpin for Builder<G>
where G: Unpin, Vec<Route<<G as Gate>::Identity, <G as Gate>::Rule>>: Unpin, Vec<(Hook, Routes, Arc<dyn Fn(&mut Cx<'_, <G as Gate>::Identity>) -> Result<(), Error> + Send + Sync>)>: Unpin,

§

impl<G> UnsafeUnpin for Builder<G>
where G: UnsafeUnpin, Vec<Route<<G as Gate>::Identity, <G as Gate>::Rule>>: UnsafeUnpin, Vec<(Hook, Routes, Arc<dyn Fn(&mut Cx<'_, <G as Gate>::Identity>) -> Result<(), Error> + Send + Sync>)>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.