Talking HTTP in the Internet
local graph
Chapter 6 — Talking HTTP in the Internet
Section titled “Chapter 6 — Talking HTTP in the Internet”The single most important application-layer protocol that has changed our lives heavily has to be the HTTP. It forms the backbone of the World Wide Web (WWW). In this chapter, we will look at how Rust makes writing fast HTTP servers easier. We will also look at writing clients to communicate with these servers over a network.
We will cover the following topics in this chapter:
- A short introduction to Hyper, one of the most widely used crates for writing HTTP servers
- We will study Rocket, a new crate that has become widely popular owing to its simpler interface
- We will move on to reqwest, an HTTP client library
Hyper is arguably the most stable and well-known of Rust-based HTTP frameworks. It has two distinct components, one for writing HTTP servers and one for writing clients. Recently, the server component was moved to a new async programming model based on tokio and futures. As a result, it is well-suited for high-traffic workloads. However, like a lot of other libraries in the ecosystem, Hyper has not hit Version 1.0 yet, so one should expect breaking API changes.
We will start with writing a small HTTP server in Hyper. Like always, we will need to set up our project using Cargo.
$ cargo new --bin hyper-serverLet us now add dependencies that will include hyper and futures. The Cargo.toml file will look as follows:
[package]name = "hyper-server"version = "0.1.0"authors = ["Foo<[email protected]>"]
[dependencies]hyper = "0.11.7"futures = "0.1.17"Our main file is pretty simple. In the real world, HTTP servers often talk to a backend, and all that can take a while to complete. Thus, it is common for replies to be a bit delayed. We will simulate that using a function that sleeps for 200 ms each time it is called, and then returns a fixed string.
extern crate hyper;extern crate futures;
use std::{ thread, time };use futures::future::FutureResult;use hyper::{Get, StatusCode};use hyper::header::ContentLength;use hyper::server::{Http, Service, Request, Response};
// Simulate CPU intensive work by sleeping for 200 msfn heavy_work() -> String { let duration = time::Duration::from_millis(200); thread::sleep(duration); "done".to_string()}
#[derive(Clone, Copy)]struct Echo;
impl Service for Echo { type Request = Request; type Response = Response; type Error = hyper::Error; type Future = FutureResult<Response, hyper::Error>;
// This method handles actually processing requests // We only handle GET requests on /data and ignore everything else // returning a HTTP 404 fn call(&self, req: Request) -> Self::Future { futures::future::ok(match (req.method(), req.path()) { (&Get, "/data") => { let b = heavy_work().into_bytes(); Response::new() .with_header(ContentLength(b.len() as u64)) .with_body(b)} _ => Response::new().with_status(StatusCode::NotFound),}) }}
fn main() { let addr = "0.0.0.0:3000".parse().unwrap(); let server = Http::new().bind(&addr, || Ok(Echo)).unwrap(); server.run().unwrap();}As Hyper heavily relies on tokio to do asynchronous handling of requests, an HTTP server in Hyper needs to implement a built-in trait called Service from tokio. This is essentially a function that maps a Request to a Response via an implementation of the call method. This method returns the result as a Future, indicating eventual completion of the given task. In that implementation, we match the method and path of the incoming request. If the method is GET and the path is /data, we call heavy_work and get the result. We then compose a response by setting the Content-Length header to the size of the string we are returning and the body of the response. In our main function, we construct our server by binding it to a known port. At the end, we call run on it to start the server.
Interacting with the server is easy with curl; a session should look like this:
$ curl http://127.0.0.1:3000/datadone$Let us benchmark our server. For this, we will install ApacheBench (https://httpd.apache.org/docs/trunk/programs/ab.html). We will run 1,000 total requests from 100 clients in parallel by passing some command-line parameters to ApacheBench. This will take a while to complete, and we are waiting 200 ms before returning each response. So, for 1,000 requests, we will wait for at least 200 seconds. On one run, the output looks like this:
$ ab -n 1000 -c 100 http://127.0.0.1:3000/dataBenchmarking 127.0.0.1 (be patient)Completed 100 requestsCompleted 200 requestsCompleted 300 requestsCompleted 400 requestsCompleted 500 requestsCompleted 600 requestsCompleted 700 requestsCompleted 800 requestsCompleted 900 requestsCompleted 1000 requestsFinished 1000 requests
Server Software:Server Hostname: 127.0.0.1Server Port: 3000
Document Path: /dataDocument Length: 4 bytes
Concurrency Level: 100Time taken for tests: 203.442 secondsComplete requests: 1000Failed requests: 0Total transferred: 79000 bytesHTML transferred: 4000 bytesRequests per second: 4.92 [#/sec] (mean)Time per request: 20344.234 [ms] (mean)Time per request: 103.442 [ms] (mean, across all concurrent requests)Transfer rate: 0.38 [Kbytes/sec] received
Connection Times (ms)min mean[+/-sd] median maxConnect: 0 2 0.7 2 3Processing: 5309 20123 8061.9 20396 33029Waiting: 203 12923 5518.0 14220 20417Total: 5311 20124 8061.9 20397 33029
Percentage of the requests served within a certain time (ms) 50% 20397 66% 25808 75% 26490 80% 27263 90% 28373 95% 28568 98% 33029 99% 33029 100% 33029 (longest request)Notice that, across all requests, the server takes around 103.4 ms to reply back. This matches our expectation of 100 ms with the extra time being spent on other things. Also, our server is processing 4.92 requests per second, which is way too low for a reasonable server. This is all because our server is single-threaded, and only one thread serves all clients. This server also ignores the fact that multiple CPU cores are available on the host.
Let us go ahead and write a server that largely does the same thing, the difference being that this one uses multi-threading heavily and uses all CPU cores. Cargo setup should be as follows:
$ cargo new --bin hyper-server-fasterWe will need to add some more crates as dependencies, and our Cargo.toml should be as follows:
[package]name = "hyper-server-faster"version = "0.1.0"authors = ["Foo<[email protected]>"]
[dependencies]hyper = "0.11.7"futures = "0.1.17"net2 = "0.2.31"tokio-core = "0.1.10"num_cpus = "1.0"We have a number of extra things here. tokio-core will be used to run an event loop (as we did in mio, in Chapter 3, TCP and UDP Using Rust), net2 will be used for some advanced socket configuration, and num_cpus will be used to figure out the number of CPU cores on the machine. Having set those up, our main file is pretty simple:
extern crate futures;extern crate hyper;extern crate net2;extern crate tokio_core;extern crate num_cpus;
use futures::Stream;use net2::unix::UnixTcpBuilderExt;use tokio_core::reactor::Core;use tokio_core::net::TcpListener;use std::{thread, time};use std::net::SocketAddr;use std::sync::Arc;use futures::future::FutureResult;use hyper::{Get, StatusCode};use hyper::header::ContentLength;use hyper::server::{Http, Service, Request, Response};
// Same method like last examplefn heavy_work() -> String { let duration = time::Duration::from_millis(200); thread::sleep(duration); "done".to_string()}
#[derive(Clone, Copy)]struct Echo;
impl Service for Echo { type Request = Request; type Response = Response; type Error = hyper::Error; type Future = FutureResult<Response, hyper::Error>;
fn call(&self, req: Request) -> Self::Future { futures::future::ok(match (req.method(), req.path()) { (&Get, "/data") => { let b = heavy_work().into_bytes(); Response::new() .with_header(ContentLength(b.len() as u64)) .with_body(b) } _ => Response::new().with_status(StatusCode::NotFound), }) }}
// One server instancefn serve(addr: &SocketAddr, protocol: &Http) { let mut core = Core::new().unwrap(); let handle = core.handle(); let listener = net2::TcpBuilder::new_v4() .unwrap() .reuse_port(true) .unwrap() .bind(addr) .unwrap() .listen(128) .unwrap(); let listener = TcpListener::from_listener(listener, addr, &handle).unwrap(); core.run(listener.incoming().for_each(|(socket, addr)| { protocol.bind_connection(&handle, socket, addr, Echo); Ok(()) })).unwrap();}
// Starts num number of serving threadsfn start_server(num: usize, addr: &str) { let addr = addr.parse().unwrap();
let protocol = Arc::new(Http::new()); { for _ in 0..num - 1 { let protocol = Arc::clone(&protocol); thread::spawn(move || serve(&addr, &protocol)); } } serve(&addr, &protocol);}
fn main() { start_server(num_cpus::get(), "0.0.0.0:3000");}Functionally, this server is exactly the same as the last one. Architecturally, they are very different. Our implementation of Service is the same. What changed majorly is that we split starting the server into two functions; the serve function creates a new event loop (and a handle to it). We create our listener using net2 so that we can set a bunch of options on it using the TcpBuilder pattern. Specifically, we set SO_REUSEPORT on the socket so that under high loads the OS can distribute connections to all threads fairly. We also set a backlog of 128 for the listening socket. We then loop over incoming connections on the listener and, for each, we run our service implementation. Our start_server method takes in an integer that corresponds to the number of cores on the host and an address as a string. We then start a loop and run the serve method in new threads. In this case, our Http instance will be passed to multiple threads. Thus, we need to wrap it in an Automatically Reference Counting (ARC) pointer because that guarantees thread safety of the underlying type. Finally, we call start_server in our main function, using num_cpus::get to get the number of cores on the machine.
Benchmarking this in the same way as last time shows these results:
$ ab -n 1000 -c 100 http://127.0.0.1:3000/dataBenchmarking 127.0.0.1 (be patient)Completed 100 requestsCompleted 200 requestsCompleted 300 requestsCompleted 400 requestsCompleted 500 requestsCompleted 600 requestsCompleted 700 requestsCompleted 800 requestsCompleted 900 requestsCompleted 1000 requestsFinished 1000 requests
Server Software:Server Hostname: 127.0.0.1Server Port: 3000
Document Path: /dataDocument Length: 4 bytes
Concurrency Level: 100Time taken for tests: 102.724 secondsComplete requests: 1000Failed requests: 0Total transferred: 79000 bytesHTML transferred: 4000 bytesRequests per second: 9.73 [#/sec] (mean)Time per request: 10272.445 [ms] (mean)Time per request: 102.724 [ms] (mean, across all concurrent requests)Transfer rate: 0.75 [Kbytes/sec] received
Connection Times (ms) min mean[+/-sd] median maxConnect: 0 2 1.0 2 6Processing: 304 10036 1852.8 10508 10826Waiting: 106 5482 2989.3 5458 10316Total: 305 10038 1852.7 10510 10828
Percentage of the requests served within a certain time (ms) 50% 10510 66% 10569 75% 10685 80% 10686 90% 10756 95% 10828 98% 10828 99% 10828 100% 10828 (longest request)This server’s throughput is around double the last one, primarily because it uses threading better. Requests still take just over 100 ms to process, as expected. Note that the actual time taken by this will depend on the hardware and conditions of the machine running this.
Perhaps the most widely known web framework for Rust is Rocket. It started as a one-man project and gradually evolved into a simple, elegant, and fast framework over the last year or so. Rocket focuses a lot on simplicity, something that a lot of Flask users will appreciate. Like Flask uses python decorators to declare routes, Rocket uses custom attributes to the same effect. Unfortunately, this means that Rocket has to make heavy use of nightly-only features. Thus, as of now, Rocket applications can only be built using nightly Rust. However, as more and more things are stabilized (moved to stable Rust), this restriction will eventually go away.
Let us start with a basic example of Rocket, beginning with setting up the project:
$ cargo new --bin rocket-simpleOur Cargo setup needs to add Rocket components as dependencies, and should look like this:
[package]name = "rocket-simple"version = "0.1.0"authors = ["Foo <[email protected]>"]
[dependencies]rocket = "0.3.6"rocket_codegen = "0.3.6"Let us look at the main file. As we will see, Rocket needs a bit of boilerplate setup:
#![feature(plugin)]#![plugin(rocket_codegen)]
extern crate rocket;
#[get("/")]fn blast_off() -> &'static str { "Hello, Rocket!"}
fn main() { rocket::ignite().mount("/", routes![blast_off]).launch();}The function called blast_off defines a route, a mapping between an incoming request and an output. In this case, a GET request to the / route should return a static string. In our main function, we initialize Rocket, add our routes, and call launch. Run it using Cargo:
$ cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs Running \`target/debug/rocket-simple\`Configured for development. => address: localhost => port: 8000 => log: normal => workers: 16 => secret key: generated => limits: forms = 32KiB => tls: disabledMounting '/': => GET /Rocket has launched from http://localhost:8000In another terminal, if we use curl to hit that endpoint, this is what we should see:
$ curl http://localhost:8000Hello, Rocket!$Experienced Python users will find Rocket similar to the framework called Flask.
Let us now look at a more complex example: writing an API server using Rocket. Our application is a blog server that has the following endpoints:
| Endpoint | Method | Purpose |
|---|---|---|
| /posts | GET | Get all posts |
| /posts/<id> | GET | Get the post with the given ID |
| /posts | POST | Add a new post |
| /posts/<id> | PATCH | Edit a post |
| /posts/<id> | DELETE | Delete the post with the given ID |
For this example, we will use SQLite Version 3 as our database. A real application should use a more scalable database, such as PostgresSQL or MySQL. We will use the diesel crate as our Object-Relational Mapping (ORM) tool, and r2d2 for connection-pooling to the database. The first step for this is to install the diesel CLI to work with database schema migrations. This can be installed using Cargo.
$ cargo install diesel_cli --no-default-features --features sqliteSQLite Version 3 must be installed on the host’s system for this to work. For more information, visit the following link:
https://www.sqlite.org/download.html
Now we can set up our database using diesel CLI. It will read our migration scripts and create the whole schema. As SQLite is a file-based database, it will also create an empty db file, if one does not exist already.
$ DATABASE_URL=db.sql diesel migration runRemember that the last command must be run from the directory that has the migrations directory, otherwise it will fail to find the migrations. We will use Cargo to set up the project:
$ cargo new --bin rocket-blogWe will then add a number of dependencies here; Cargo.toml should look like the following code snippet:
[package]authors = ["Foo <[email protected]>"]name = "rocket-blog"version = "0.1.0"
[dependencies]rocket = "0.3.5"rocket_codegen = "0.3.5"rocket_contrib = "0.3.5"diesel = { version = "0.16.0", features = ["sqlite"] }diesel_codegen = { version = "0.16.0", features = ["sqlite"] }dotenv = "0.10.1"serde = "1.0.21"serde_json = "1.0.6"serde_derive = "1.0.21"lazy_static = "0.2.11"r2d2 = "0.7.4"r2d2-diesel = "0.16.0"This app is a bit more complex than our previous example. This is composed of multiple modules, each doing a specific thing. Here is how the src directory looks:
$ tree src/src/├── db.rs├── error.rs├── main.rs├── models.rs├── post.rs└── schema.rsThe first step in running this is to set up connection to the database. We will use r2d2 for database pooling; all the db setup-related operations will be in db.rs. This will look like the following code snippet:
use dotenv::dotenv;use std::env;use diesel::sqlite::SqliteConnection;use r2d2;use r2d2_diesel::ConnectionManager;use rocket::request::{Outcome, FromRequest};use rocket::Outcome::{Success, Failure};use rocket::Request;use rocket::http::Status;
// Statically initialize our DB poollazy_static! { pub static ref DB_POOL: r2d2::Pool<ConnectionManager<SqliteConnection>> = { dotenv().ok();
let database_url = env::var("DATABASE_URL"). expect("DATABASE_URL must be set"); let config = r2d2::Config::builder() .pool_size(32) .build(); let manager = ConnectionManager:: <SqliteConnection>::new(database_url); r2d2::Pool::new(config, manager).expect("Failed to create pool.") };}
pub struct DB(r2d2::PooledConnection<ConnectionManager<SqliteConnection>>);
// Make sure DB pointers deref nicelyimpl Deref for DB { type Target = SqliteConnection;
fn deref(&self) -> &Self::Target { &self.0 }}
impl<'a, 'r> FromRequest<'a, 'r> for DB { type Error = r2d2::GetTimeout; fn from_request(_: &'a Request<'r>) -> Outcome<Self, Self::Error> { match DB_POOL.get() { Ok(conn) => Success(DB(conn)), Err(e) => Failure((Status::InternalServerError, e)), } }}Our DB struct has an instance of the database pool and returns that on calling the function called conn. FromRequest. This is a request guard trait from Rocket that makes sure that particular requests can be fulfilled by the handler that matched. In our case, we use it to make sure a new connection is available in the pool, and we return an HTTP 500 error if that is not the case. Now this trait will be used for all incoming requests throughout the life of the program. Thus, for this to work correctly, the reference to the database pool must live throughout the program and not the local scope. We use the lazy_static! crate to make sure the constant DB_POOL is initialized only once and lives throughout the life of the program. In the macro, we set up dotenv, which will be used later to parse the database location and also the connection pool with a size of 32 connections. We also implement the Deref trait for our database wrapper so that &*DB is transparently translated to a &SqliteConnection.
The next step is to set up the database schema in code. Luckily, diesel makes that very easy, as it can read the database schema and generate Rust code to represent that accordingly. The generated Rust code is put in a module corresponding to the name of the file it is in (in this case, the module will be called schema). We use the dotenv crate to pass this information to a diesel macro. This is done in the file schema.rs:
infer_schema!("dotenv:DATABASE_URL");Note that once the new macro system is functional, this call will use the dotenv! macro. We can then use the generated schema to build our models. This is done in models.rs. This file will look like the following code snippet:
use super::schema::posts;use rocket::{Request, Data};use rocket::data::{self, FromData};use rocket::http::Status;use rocket::Outcome::*;use serde_json;
// Represents a blog post in the database#[derive(Queryable)]#[derive(Serialize,Deserialize)]pub struct Post { pub id: i32, pub title: String, pub body: String, pub pinned: bool,}
// Represents a blog post as incoming request data#[derive(Insertable, Deserialize, AsChangeset)]#[table_name="posts"]pub struct PostData { pub title: String, pub body: String, pub pinned: bool,}
// This enables using PostData from incoming request dataimpl FromData for PostData { type Error = String;
#[allow(unused_variables)] fn from_data(req: &Request, data: Data) -> data::Outcome<Self, String> { let reader = data.open(); match serde_json::from_reader(reader).map(|val| val) { Ok(value) => Success(value), Err(e) => Failure((Status::BadRequest, e.to_string())), } }}We have two major structures here: the Post structure represents a blog post in the database, and the PostData structure represents a blog post as seen in an incoming create request. As a PostData has not been saved in the database yet, it does not have an ID. Diesel necessitates that all types that can be queried should implement the Queryable trait, which is done automatically using #[derive(Queryable)]. We also enable serialization and deserialization using serde, as this will be passed as JSON to the API. In contrast, the PostData struct does not derive Queryable; it derives some other traits. The Insertable trait indicates that this struct can be used to insert a row of data in a table (with the specified table name). Because we will only need to deserialize this struct from an incoming request, we only implement Deserialize on it. Lastly, the AsChangeSet trait enables this struct to be used to update records in the database.
The FromData trait is from Rocket, which is used to validate incoming data, making sure it parses into JSON correctly. This is in relation to a feature called data guards. When Rocket finds a suitable handler for an incoming request, it calls the data guard of the data type specified in the request handler on the incoming data. The route is actually invoked only if the data guard succeeds. These guards are implemented using the FromData trait. In our case, the implementation tries to parse the input as a JSON (using SerDe). In the success case, we return the JSON for further processing, or we return a Status::BadRequest, which sends back an HTTP 400 error.
The only database-related thing required now is the model. This will define a number of convenience methods that can be used to manipulate records using diesel. The file post.rs hosts these, and it looks like the following code snippet:
use diesel::result::Error;use diesel;use diesel::sqlite::SqliteConnection;use models::*;use diesel::prelude::*;use schema::posts;
// Returns post with given idpub fn get_post(conn: &SqliteConnection, id: i32) -> Result<Post, Error> { posts::table .find(id) .first::<Post>(conn)}
// Returns all postspub fn get_posts(conn: &SqliteConnection) -> Result<Vec<Post>, Error> { posts::table .load::<Post>(conn)}
// Creates a post with the given PostData, assigns a IDpub fn create_post(conn: &SqliteConnection, post: PostData) -> bool { diesel::insert(&post) .into(posts::table).execute(conn).is_ok()}
// Deletes a post with the given IDpub fn delete_post(conn: &SqliteConnection, id: i32) -> Result<usize, Error> { diesel::delete(posts::table.find(id)) .execute(conn)}
// Updates a post with the given ID and PostDatapub fn update_post(conn: &SqliteConnection, id: i32, updated_post: PostData) -> bool { diesel::update(posts::table .find(id)) .set(&updated_post).execute(conn).is_ok()}The function names are very self-explanatory. We make abundant use of a number of diesel APIs that help us to interact with the database without writing SQL directly. All of these functions take in a reference to the database connection. The get_post function takes in an additional post ID that it uses on the posts table to look up posts using the find method, and then returns the first result as an instance of Post. The get_posts function is similar, except it returns all records in the posts table as a vector of Post instances. create_post takes in a reference to PostData and inserts that record into the database. This function returns a bool indicating success or failure. delete_post takes in a post ID and tries to delete it in the database. update_post again takes in a reference to PostData and a post ID. It then tries to replace the post with the given ID with the new PostData.
Let us move on to defining errors for our API. This will be located in the file called error.rs. As will see here, the errors will need to implement a number of traits to be used seamlessly in Rocket and Diesel.
use std::error::Error;use std::convert::From;use std::fmt;use diesel::result::Error as DieselError;use rocket::http::Status;use rocket::response::{Response, Responder};use rocket::Request;
#[derive(Debug)]pub enum ApiError { NotFound, InternalServerError,}
impl fmt::Display for ApiError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ApiError::NotFound => f.write_str("NotFound"), ApiError::InternalServerError => f.write_str("InternalServerError"), } }}
// Translates a database error to an API errorimpl From<DieselError> for ApiError { fn from(e: DieselError) -> Self { match e { DieselError::NotFound => ApiError::NotFound, _ => ApiError::InternalServerError, } }}
impl Error for ApiError { fn description(&self) -> &str { match *self { ApiError::NotFound => "Record not found", ApiError::InternalServerError => "Internal server error", } }}
// This enables sending back an API error from a routeimpl<'r> Responder<'r> for ApiError { fn respond_to(self, _request: &Request) -> Result<Response<'r>, Status> { match self { ApiError::NotFound => Err(Status::NotFound), _ => Err(Status::InternalServerError), } }}Our error is an enum called ApiError; for simplicity’s sake, we will only return an object-not-found error and a catch-all internal server error. As we have seen in previous chapters, to declare an error in Rust, we will need to implement fmt::Display and std::error::Error on that type. We also implement From<DieselError> for our type so that a failure in the database lookup can be reported appropriately. The final trait we need to implement is Responder from Rocket, which enables us to use this as the return type of a request handler.
Having done all the groundwork, the last part of the system is our main file that will run when invoked with Cargo. It should look like the following code snippet:
#![feature(plugin)]#![plugin(rocket_codegen)]extern crate rocket;#[macro_use]extern crate diesel;#[macro_use]extern crate diesel_codegen;extern crate dotenv;extern crate serde_json;#[macro_use]extern crate lazy_static;extern crate rocket_contrib;#[macro_use]extern crate serde_derive;extern crate r2d2;extern crate r2d2_diesel;
mod schema;mod db;mod post;mod models;mod error;
use db::DB;use post::{get_posts, get_post, create_post, delete_post, update_post};use models::*;use rocket_contrib::Json;use rocket::response::status::{Created, NoContent};use rocket::Rocket;use error::ApiError;
#[get("/posts", format = "application/json")]fn posts_get(db: DB) -> Result<Json<Vec<Post>>, ApiError> { let posts = get_posts(&db)?; Ok(Json(posts))}
#[get("/posts/<id>", format = "application/json")]fn post_get(db: DB, id: i32) -> Result<Json<Post>, ApiError> { let post = get_post(&db, id)?; Ok(Json(post))}
#[post("/posts", format = "application/json", data = "<post>")]fn post_create(db: DB, post: PostData) -> Result<Created<String>, ApiError> { let post = create_post(&db, post); let url = format!("/post/{}", post); Ok(Created(url, Some("Done".to_string())))}
#[patch("/posts/<id>", format = "application/json", data = "<post>")]fn post_edit(db: DB, id: i32, post: PostData) -> Result<Json<bool>, ApiError> { let post = update_post(&db, id, post); Ok(Json(post))}
#[delete("/posts/<id>")]fn post_delete(db: DB, id: i32) -> Result<NoContent, ApiError> { delete_post(&db, id)?; Ok(NoContent)}
// Helper method to setup a rocket instancefn rocket() -> Rocket { rocket::ignite().mount("/", routes![post_create, posts_get, post_delete, post_edit, post_get])}
fn main() { rocket().launch();}The most important things here are the route handlers. These are just regular functions with special attributes that determine the path, the format, and the arguments. Also, notice the use of instances of DB as request guards in the handlers. We have a helper function called rocket that sets up everything, and the main function just calls the ignite method to start the server. When rocket sees an incoming request, this is how a response is generated:
- It goes over the list of all handlers and finds one that matches the HTTP method, type, and format. If one is found, it ensures that the handler’s parameters can be derived from the data in the request using FormData. This process continues till a handler works or all handlers have been exhausted. In the latter case, a 404 error is returned.
- The handler function then receives a copy of the data parsed into the given data type. After it has done processing, it must use the Responder implementation to convert the output to a valid return type.
- Finally, Rocket sends back the response to the client.
Having set up everything, running the server is very easy:
$ DATABASE_URL=db.sql cargo runYou can use curl to interact with the server, as shown in the following code snippet. We use jq for formatting the JSON nicely by piping curl’s output to jq:
$ curl -X POST -H "Content-Type: application/json" -d '{"title": "Hello Rust!", "body": "Rust is awesome!!", "pinned": true}' http://localhost:8000/postsDone$ curl http://localhost:8000/posts | jq % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed100 130 100 130 0 0 130 0 0:00:01 --:--:-- 0:00:01 8125[ { "id": 1, "title": "test", "body": "test body", "pinned": true }, { "id": 2, "title": "Hello Rust!", "body": "Rust is awesome!!", "pinned": true }]For comparison, here is how a load testing session looks:
$ ab -n 10000 -c 100 http://localhost:8000/postsBenchmarking localhost (be patient)Completed 1000 requestsCompleted 2000 requestsCompleted 3000 requestsCompleted 4000 requestsCompleted 5000 requestsCompleted 6000 requestsCompleted 7000 requestsCompleted 8000 requestsCompleted 9000 requestsCompleted 10000 requestsFinished 10000 requests
Server Software: RocketServer Hostname: localhostServer Port: 8000
Document Path: /postsDocument Length: 130 bytes
Concurrency Level: 100Time taken for tests: 2.110 secondsComplete requests: 10000Failed requests: 0Total transferred: 2740000 bytesHTML transferred: 1300000 bytesRequests per second: 4740.00 [#/sec] (mean)Time per request: 21.097 [ms] (mean)Time per request: 0.211 [ms] (mean, across all concurrent requests)Transfer rate: 1268.32 [Kbytes/sec] received
Connection Times (ms) min mean[+/-sd] median maxConnect: 0 0 0.4 0 4Processing: 3 21 20.3 19 229Waiting: 2 20 19.8 18 228Total: 7 21 20.3 19 229
Percentage of the requests served within a certain time (ms) 50% 19 66% 19 75% 20 80% 20 90% 21 95% 22 98% 26 99% 214 100% 229 (longest request)Now, to be fair to our earlier servers, we had a delay of 100 ms there. In this case, each request takes around 21 ms on average. So, hypothetically, if each request took 100 ms, we would have one fifth of the throughput. That comes up to be around 950 requests per second—way faster than our earlier servers!
Now, obviously, an HTTP server cannot be all about REST endpoints. It must be able to serve static and dynamic content as well. For that, Rocket has a bunch of features to be able to generate HTML. Let us look at an example, which is a simple web page that takes in a name as a URL parameter and outputs that. The page also counts the total number of visits and displays that as well. The Cargo setup for this project is simple: we just run the following command:
$ cargo new --bin rocket-templatesThis time, we will just need Rocket in our Cargo.toml file:
[package]authors = ["Foo<[email protected]>"]name = "rocket-templates"version = "0.1.0"
[dependencies]rocket = "0.3.5"rocket_codegen = "0.3.5"
[dependencies.rocket_contrib]version = "*"default-features = falsefeatures = ["tera_templates"]Our web page will be generated from a template. We will use a templating engine called Tera, which is inspired by Jinja2 and is written in Rust. Rocket supports templates in a different crate called rocket_contrib, which we will pull in with required features. Our template is pretty simple and should look like this:
<!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title>Rocket template demo</title> </head> <body> <h1>Hi {{name}}, you are visitor number {{ visitor_number }}</h1> </body></html>Note that the template has to be in a directory called templates in the project root, otherwise Rocket will not be able to find it. In this case, the template is pretty simple. It needs to be a complete HTML page, as we intend to display it in a browser. We use two temporary variables, name and visitor_number, that will be replaced during execution. Our main file will look like the following code snippet:
#![feature(plugin)]#![plugin(rocket_codegen)]
extern crate rocket_contrib;extern crate rocket;
use rocket_contrib::Template;use rocket::{Rocket, State};use std::collections::HashMap;use std::sync::atomic::{AtomicUsize, Ordering};
struct VisitorCounter { visitor_number: AtomicUsize,}
#[get("/webpage/<name>")]fn webpage(name: String, visitor: State<VisitorCounter>) -> Template { let mut context = HashMap::new(); context.insert("name", name); let current = visitor.visitor_number.fetch_add(1, Ordering::SeqCst); context.insert("visitor_number", current.to_string()); Template::render("webpage", &context)}
fn rocket() -> Rocket { rocket::ignite() .manage(VisitorCounter { visitor_number: AtomicUsize::new(1) }) .mount("/", routes![webpage]) .attach(Template::fairing())}
fn main() { rocket().launch();}Our setup is pretty much the same as last time; the only difference being, we have used the template fairing, which is like a middleware in Rocket. To use this, we needed to call attach(Template::fairing()) on the rocket instance. Another difference is the use of managed state, which we use to manage our counter automatically. This is achieved by calling manage on the instance and passing an initial state for the managed object. Our counter is a struct, having only one element that holds the current count. Now our counter will be shared between multiple threads, all running rocket instances. To make the counter thread safe, we have used the primitive AtomicUsize, which guarantees thread safety. In our route, we match on the GET verb and we take in a name as a URL parameter. To render our template, we will need to build a context and populate it. Whenever an incoming request matches this route, we can insert the name in our context. We then call fetch_add on the underlying counter. This method increments the counter and returns the previous value, which we store in the context against a key called visitor_number. Once done, we can render our template, which is returned to the client. Note the use of Ordering::SeqCst in fetch_add, which guarantees a sequentially consistent view of the counter across all competing threads. Also note that the names of the keys in the context have to match the temporary variables used in the template, otherwise rendering will fail.
Running this is easy; we just need to use cargo run. This is what we see on the CLI:
$ cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs Running \`target/debug/rocket-templates\`Configured for development. => address: localhost => port: 8000 => log: normal => workers: 16 => secret key: generated => limits: forms = 32KiB => tls: disabledMounting '/': => GET /webpage/<name>Rocket has launched from http://localhost:8000We can then use a web browser to access the page to see something like the following screenshot:

Notice that the counter resets when the Rocket instance is restarted. A real-world application may decide to persist such a metric in a database so that it is not lost between restarts. This also works with curl, which just dumps the raw HTML in the console:
$ curl http://localhost:8000/webpage/foo<!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title>Rocket template demo</title> </head> <body> <h1>Hi foo, you are visitor number 2</h1> </body></html>The last experiment with this piece of code is performance analysis. As always, we will fire up apache bench and point it to the endpoint. This is what one run shows:
$ ab -n 10000 -c 100 http://localhost:8000/webpage/foobarBenchmarking localhost (be patient)Completed 1000 requestsCompleted 2000 requestsCompleted 3000 requestsCompleted 4000 requestsCompleted 5000 requestsCompleted 6000 requestsCompleted 7000 requestsCompleted 8000 requestsCompleted 9000 requestsCompleted 10000 requestsFinished 10000 requests
Server Software: RocketServer Hostname: localhostServer Port: 8000
Document Path: /webpage/foobarDocument Length: 191 bytes
Concurrency Level: 100Time taken for tests: 2.305 secondsComplete requests: 10000Failed requests: 0Total transferred: 3430000 bytesHTML transferred: 1910000 bytesRequests per second: 4337.53 [#/sec] (mean)Time per request: 23.055 [ms] (mean)Time per request: 0.231 [ms] (mean, across all concurrent requests)Transfer rate: 1452.90 [Kbytes/sec] received
Connection Times (ms) min mean[+/-sd] median maxConnect: 0 0 2.8 0 200Processing: 3 23 18.6 21 215Waiting: 3 22 18.0 20 214Total: 7 23 18.8 21 215
Percentage of the requests served within a certain time (ms) 50% 21 66% 21 75% 22 80% 22 90% 24 95% 25 98% 28 99% 202 100% 215 (longest request)Performance in this case is comparable to last time, as measured in requests per second. This one is slightly slower, as it has to increment the counter and render the template each time. This is also reflected in mean time per request, which increased by 2 ms.
Rocket has a ton of other features, from cookies to streaming data. It also supports SSL out of the box by reading a special config file that can be placed in the root directory of the application. However, those advanced features are outside the scope of this book.
So far, we have only talked about writing servers and used curl to access those. Sometimes, programmatically accessing a server becomes a necessity. In this section, we will discuss the reqwest crate and look at how to use it; this borrows heavily from the requests library in Python. Thus, it is very easy to set up and use, starting first with the project setup:
$ cargo new --bin reqwest-exampleThe next step for our demo is to include our dependencies. Our Cargo config should look like this:
[package]name = "reqwest-example"version = "0.1.0"authors = ["Foo<[email protected]>"]
[dependencies]reqwest = "0.8.1"serde_json = "1.0.6"serde = "1.0.21"serde_derive = "1.0.21"Here, we will use Serde to serialize and deserialize our data to JSON. Very conveniently, we will use the Rocket server we wrote in the last section. Our main file will look like this:
extern crate serde_json;#[macro_use]extern crate serde_derive;extern crate reqwest;
#[derive(Debug,Serialize, Deserialize)]struct Post { title: String, body: String, pinned: bool,}
fn main() { let url = "http://localhost:8000/posts"; let post: Post = Post {title: "Testing this".to_string(), body: "Try to write something".to_string(), pinned: true}; let client = reqwest::Client::new();
// Creates a new blog post using the synchronous client let res = client.post(url) .json(&post) .send() .unwrap(); println!("Got back: {}", res.status());
// Retrieves all blog posts using the synchronous client let mut posts = client.get(url).send().unwrap(); let json: Vec<Post> = posts.json().unwrap(); for post in json { println!("{:?}", post); }}We start with a struct to represent our blog post, which is exactly the same as the one in the last section. In our main function, we create an instance of our client and, using the builder pattern, pass on our post as a JSON to it. Finally, we call send on it and print out the return status. Make sure to change the url to point to the location where Rocket is running. We then issue a GET request on the same endpoint. We deserialize the response to a list of Post objects and print those out in a loop. Internally, reqwest uses SerDe to serialize and deserialize to/from JSON, making the API very user-friendly.
Here is an example session running the preceding code. In our server, we already had two existing entries and, in our code, we added one more. Then, we got back all three, which are printed here. Take a look at the following code snippet:
$ cargo run Compiling reqwest-example v0.1.0 (file:///src/ch6/reqwest-example) Finished dev [unoptimized + debuginfo] target(s) in 1.94 secs Running \`target/debug/reqwest-example\`Got back: 201 CreatedPost { title: "test", body: "test body", pinned: true }Post { title: "Hello Rust!", body: "Rust is awesome!!", pinned: true }Post { title: "Testing this", body: "Try to write something", pinned: true }Recently, reqwest added asynchronous programming support using tokio. All those APIs are located in reqwest::unstable and, as the name suggests, those are not stable yet. Let’s look at using the asynchronous client for the same purpose. In this case, we will use the futures and tokio crates, thus we will need to include those in our cargo manifest, which will look like this:
[package]name = "reqwest-async"version = "0.1.0"authors = ["Foo <[email protected]>"]
[dependencies]serde_json = "1.0.6"serde = "1.0.21"serde_derive = "1.0.21"futures = "0.1.17"tokio-core = "0.1.10"
[dependencies.reqwest]version = "0.8.1"features = ["unstable"]We will need to activate the feature called unstable in reqwest. Our main file will look like the following code snippet:
extern crate serde_json;#[macro_use]extern crate serde_derive;extern crate reqwest;extern crate futures;extern crate tokio_core;
use futures::Future;use tokio_core::reactor::Core;use reqwest::unstable::async::{Client, Decoder};use std::mem;use std::io::{self, Cursor};use futures::Stream;
#[derive(Debug, Serialize, Deserialize)]struct Post { title: String, body: String, pinned: bool,}
fn main() { let mut core = Core::new().expect("Could not create core"); let url = "http://localhost:8000/posts"; let post: Post = Post { title: "Testing this".to_string(), body: "Try to write something".to_string(), pinned: true, }; let client = Client::new(&core.handle());
// Creates a new post using the async client let res = client.post(url).json(&post).send().and_then(|res| { println!("{}", res.status()); Ok(()) }); core.run(res).unwrap();
// Gets all current blog posts using the async client let posts = client .get(url) .send() .and_then(|mut res| { println!("{}", res.status()); let body = mem::replace(res.body_mut(), Decoder::empty()); body.concat2().map_err(Into::into) }) .and_then(|body| { let mut body = Cursor::new(body); let mut writer: Vec<u8> = vec![]; io::copy(&mut body, &mut writer).unwrap(); let posts: Vec<Post> = serde_json::from_str(std::str::from_utf8(&writer).unwrap()) .unwrap(); for post in posts { println!("{:?}", post); } Ok(()) }); core.run(posts).unwrap();}Admittedly, this is way more convoluted than the previous version! Some scaffolding for the Post struct is the same, and we pull in all the extra libraries we need. In our main function, we create a tokio core and then an asynchronous client based on that core. We chain the json and send methods like last time. Things diverge from there; for the asynchronous client, the send call returns a future. Once that future has resolved, the and_then call executes another future based on the first one. In here, we print out the status that we got back and resolve the future by returning an Ok(()). Finally, we run our future on the core.
Getting data back from the endpoint is a bit more involved, because we have to deal with returned data as well. Here, we chain calls to get and send. We then chain another future that collects the response body. The second future is then chained to another one that consumes that body and copies it over to a Vec<u8> named writer. We then convert the vector to a str using std::str::from_utf8. The str is then passed to serde_json::from_str, which tries to deserialize it into a vector of Post objects that we can then print out by iterating over those. At the end, we resolve the chain of futures by returning an Ok(()). On running, this behaves exactly like the last one.
In this chapter, we covered a number of crates that help with dealing with HTTP-based REST endpoints in Rust, using Hyper and Rocket. We also looked at programmatically accessing these endpoints, using request, which is largely based on Hyper. These crates are at various stages of development. As we saw, Rocket can only run on nightly, because it uses a bunch of features that are not stable yet. We also glossed over tokio, which powers both Hyper and Rocket.
Now, tokio, being the defacto asynchronous programming library in Rust, deserves all the attention it can get. So, we will discuss the tokio stack in detail in the next chapter.