pub fn start_server<A, F>(addr: A, handler: F) -> !
Expand description
Starts a server and uses the given requests handler.
The request handler takes a &Request
and must return a Response
to send to the user.
Note:
start_server
is meant to be an easy-to-use function. If you want more control, see theServer
struct.
§Common mistakes
The handler must capture its environment by value and not by reference ('static
). If you
use closure, don’t forget to put move
in front of the closure.
The handler must also be thread-safe (Send
and Sync
).
For example this handler isn’t thread-safe:
let mut requests_counter = 0;
rouille::start_server("localhost:80", move |request| {
requests_counter += 1;
// ... rest of the handler ...
# panic!()
})
Multiple requests can be processed simultaneously, therefore you can’t mutably access variables from the outside.
Instead you must use a Mutex
:
use std::sync::Mutex;
let requests_counter = Mutex::new(0);
rouille::start_server("localhost:80", move |request| {
*requests_counter.lock().unwrap() += 1;
// rest of the handler
})
§Panic handling in the handler
If your request handler panics, a 500 error will automatically be sent to the client.
§Panic
This function will panic if the server starts to fail (for example if you use a port that is already occupied) or if the socket is force-closed by the operating system.
If you need to handle these situations, please see Server
.