Bootstrapping a server

The Rouille framework is very simple to use. It contains start_server functions that expect a function to handle every incoming request. Let's create a main function that uses a diesel crate with an r2d2 pool feature and calls a function to handle requests:

fn main() {
env_logger::init();
let manager = ConnectionManager::<SqliteConnection>::new("test.db");
let pool = Pool::builder().build(manager).expect("Failed to create pool.");
rouille::start_server("127.0.0.1:8001", move |request| {
match handler(&request, &pool) {
Ok(response) => { response },
Err(err) => {
Response::text(err.to_string())
.with_status_code(500)
}
}
})
}

We created a ConnectionManager for a local test.db SQLite database and a Pool instance with this manager. We discussed this in previous chapters. We are interested in the line with the rouille::start_server function call. This function takes two arguments: a listening address and a closure for handling requests. We moved pool to the closure and called handler functions, which we declared underneath it to generate a response for a request with Pool as an argument.

Since handler functions have to return a Response instance, we have to return a response with a 500 status code if a handler function returns an error. Looks pretty simple, doesn't it? Let's look at a handler function declaration.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.171.107