Book Image

Rust Web Development with Rocket

By : Karuna Murti
Book Image

Rust Web Development with Rocket

By: Karuna Murti

Overview of this book

Looking for a fast, powerful, and intuitive framework to build web applications? This Rust book will help you kickstart your web development journey and take your Rust programming skills to the next level as you uncover the power of Rocket - a fast, flexible, and fun framework powered by Rust. Rust Web Development with Rocket wastes no time in getting you up to speed with what Rust is and how to use it. You’ll discover what makes it so productive and reliable, eventually mastering all of the concepts you need to play with the Rocket framework while developing a wide set of web development skills. Throughout this book, you'll be able to walk through a hands-on project, covering everything that goes into making advanced web applications, and get to grips with the ins and outs of Rocket development, including error handling, Rust vectors, and wrappers. You'll also learn how to use synchronous and asynchronous programming to improve application performance and make processing user content easy. By the end of the book, you'll have answers to all your questions about creating a web application using the Rust language and the Rocket web framework.
Table of Contents (20 chapters)
1
Part 1: An Introduction to the Rust Programming Language and the Rocket Web Framework
7
Part 2: An In-Depth Look at Rocket Web Application Development
14
Part 3: Finishing the Rust Web Application Development

Creating responses

Let's implement a custom response for the User type. In Rocket, all types that implement rocket::response::Responder can be used as a return type in a function that handles routes.

Let's take a look at the signature of the Responder trait. This trait requires two lifetimes, 'r and 'o. The result 'o lifetime must at least be equal to the 'r lifetime:

pub trait Responder<'r, 'o: 'r> {
    fn respond_to(self, request: &'r Request<'_>) -> 
    Result<'o>;
}

First, we can include the required module to be used for implementing the Responder trait for the User struct:

use rocket::http::ContentType;
use rocket::response::{self, Responder, Response};
use std::io::Cursor;

After that, add the implementation signature for the User struct:

impl<'r> Responder<'r, 'r> for &'r User {
...