Build a Website Using Rust and the Rocket Web Framework
Traducciones al EspañolEstamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.
Rust is a functional programming language noted for its high performance and capabilities in systems programming. However, with the Rocket framework, you can also use Rust for building full-functioning — and efficient — web applications.
This guide explains what Rocket is, shows you how to install it, and gets you started using it to create your own website.
What is Rocket?
Rocket is a framework for building web applications with the Rust programming language. Rust itself is noted for its type-safety and speediness, and Rocket aims to leverage those attributes to make secure and efficient web applications.
Beyond that, Rocket emphasizes an easy and minimalistic path to putting together the web application you need. It uses simple and intuitive APIs, and Rocket does its job without all of the boilerplate code. Moreover, it is an extensible framework designed for flexibility.
Before You Begin
Familiarize yourself with our Getting Started with Linode guide and complete the steps for setting your Linode’s hostname and timezone.
This guide uses
sudo
wherever possible. Complete the sections of our How to Secure Your Server guide to create a standard user account, harden SSH access, and remove unnecessary network services.Update your system:
sudo apt update && sudo apt upgrade
Throughout, this guide uses
example-app
as the name of the Rocket application. Replace it with your preferred application name.
NoteThis guide is written for non-root users. Commands that require elevated privileges are prefixed withsudo
. If you’re not familiar with thesudo
command, see the Users and Groups guide.
Install Rust
Rocket makes use of some of Rust’s more cutting-edge features. As such, you need to install the nightly build of Rust to make sure Rocket works correctly.
Install rustup, an installer for Rust. Follow the prompts the installation script presents.
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
If you do not already have Curl installed, use this command to install it first:
sudo apt install curl
Log out and log back in or run the following command to load the necessary executables into your Bash path:
source $HOME/.cargo/env
Set
nightly
as your default Rust version:rustup default nightly
Alternatively, you can set the nightly release as your default for a specific project. Once you create a project (like in the steps below) run the following command in the project directory to have it use the nightly build:
rust override set nightly
Getting Started with Rocket
In this section, you complete the following steps:
- Download and explore Rocket’s example applications
- Create your own Rocket application
Example Applications
Use Git to clone the Rocket repository. For this example, the repository is cloned into the current user’s home directory.
cd ~ git clone https://github.com/SergioBenitez/Rocket
If you do not already have Git, install it first with the following command:
sudo apt install git
Change into the resulting
Rocket
directory, and check out the latest version. You can refer to Rocket’s releases page to see the latest version.cd Rocket git checkout v0.4.7
Look through the
examples
directory for an example you would like to explore. When you have found one, change into its directory. Here, thehello_world
example is chosen.cd examples/hello_world
Run the example:
cargo run
Rocket serves the application on localhost port
8000
. To visit the application remotely, you can use an SSH tunnel:On Windows, you can use the PuTTY tool to set up your SSH tunnel. Follow the appropriate section of the Using SSH on Windows guide, replacing the example port number there with
8000
.On macOS or Linux, use the following command to set up the SSH tunnel. Replace
example-user
with your username on the application server and192.0.2.0
with the server’s IP address:ssh -L8000:localhost:8000 example-user@192.0.2.0
Now, you can visit the application in your browser by navigating to
localhost:8000
.
Create an Application
Change to the location where you would like the project directory to be created. In this case, this is the current user’s home directory.
cd ~
Create a new binary-based Rust project, then change into the new directory you created for it.
cargo new example-app --bin cd example-app
Unless noted otherwise, all subsequent commands in this guide assume you are still in the application directory.
Open the
Cargo.toml
file, and add Rocket as a dependency for the project. Use the version number for the latest version of Rocket. Refer to the Example Applications section above for how to identify the latest Rocket release.- File: ~/example-app/Cargo.toml
1 2 3 4 5
# [...] [dependencies] rocket = "0.4.7"
Open the
src/main.rs
file, and populate it with the following lines:- File: ~/example-app/src/main.rs
1 2 3 4 5 6 7 8 9 10 11 12 13
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; #[get("/")] fn index() -> &'static str { "Hello, world!" } fn main() { rocket::ignite().mount("/", routes![index]).launch(); }
You have now created a basic “Hello, World!” application, which you can test by using the
cargo run
command as shown in the Example Applications section above.
Build a Website with Rocket
Rocket can easily be set up to provide web service APIs based on the above example and referring to the official Rocket documentation.
Pairing Rocket with a template engine like Handlebars makes it ready to run a full website. The steps below show you how to do just that and set you up with the foundations for going off and building your own templates.
Follow the steps in the Create an Application section above to create a base Rocket application to work off.
Open the project’s
Cargo.toml
, and modify with the additional lines in the example below:- File: ~/example-app/Cargo.toml
1 2 3 4 5 6 7 8 9 10 11
# [...] [dependencies] rocket = "0.4.7" serde = { version = "1.0", features = ["derive"] } [dependencies.rocket_contrib] version = "*" default-features = false features = ["handlebars_templates"]
This adds
serde
, which comes with some typing features the application needs,as a dependency. Therocket_contrib
section allows Handlebars to be identified as a feature that the project uses.Open your
~/example-app/src/main.rs
file, and modify it to include the following code:- File: ~/example-app/src/main.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; use rocket::response::Redirect; use rocket_contrib::templates::Template; #[derive(serde::Serialize)] struct Message { user: &'static str, body: &'static str } #[derive(serde::Serialize)] struct BoardContext { current_user: Option<String>, messages: Vec<Message>, parent: &'static str } #[derive(serde::Serialize)] struct AboutContext { parent: &'static str } #[get("/")] fn index() -> Redirect { Redirect::to("/user/anonymous") } #[get("/user/<username>")] fn board(username: String) -> Template { Template::render("index", &BoardContext { current_user: Some(username), messages: vec![Message{user: "userA", body: "This is the first test message."}, Message{user: "userB", body: "This is the second test message."}], parent: "layout" }) } #[get("/about")] fn about() -> Template { Template::render("about", &AboutContext { parent: "layout" }) }
This creates a
Message
struct, defining the basic shape for messages. TheBoardContext
andAboutContext
structs determine “context” information to be handed off to the templates. Each context struct has aparent
attribute. The application uses these attributes in theboard
andabout
functions to apply the appropriate page layout for each page.These two functions are where the application loads the Message board and the About pages, respectively. They populate the context information and render the templates with it.
The application also uses a redirect to navigate users from the base URL (
/
) to the message board URL.
Create a template directory.
mkdir templates
Create the five template files shown below.
- The
layout.hbs
file defines the page layout used on each page. Using theparent
attribute defined in themain.rs
file’s context structs, you could also have different layouts for different sections of your site.
- File: ~/example-app/templates/layout.hbs
1 2 3 4 5 6 7 8 9 10 11 12
<!doctype html> <html> <head> <title>Example App - Message Board</title> </head> <body> {{> header}} {{~> page}} {{> footer}} </body> </html>
- The
header.hbs
andfooter.hbs
files provide contents for those sections. These are directly referenced in the page layout file, so they appear on each page of your site that uses that page layout.
- File: ~/example-app/templates/header.hbs
1 2 3 4
<nav> <a href="/">Message Board</a> | <a href="/about">About</a> </nav>
- File: ~/example-app/templates/footer.hbs
1 2 3 4
<footer> Built with Rust and the Rocket framework. </footer>
- The
index.hbs
file defines the way your main page — in this case, the Message board — gets laid out.
- File: ~/example-app/templates/index.hbs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
{{#*inline "page"}} <section id="message_board"> <h1>Hi, {{ current_user }}!</h1> You can login as a different user by navigating to "/user/{username}". <h2>Messages</h2> <ul> {{#each messages}} <li>{{ this.user }}: {{ this.body }}</li> {{/each}} </ul> </section> {{/inline}} {{~> (parent)~}}
The
about.hbs
provides the contents for the about page.- File: ~/example-app/templates/about.hbs
1 2 3 4 5 6 7 8 9 10
{{#*inline "page"}} <section id="about"> <h1>About</h1> This is an example web application built with Rust and the Rocket framework. </section> {{/inline}} {{~> (parent)~}}
- The
Now you can run the application using the
cargo run
command as shown in the Example Applications section above.
Conclusion
After completing this guide, you should have a solid understanding of how to get started using Rocket to make web applications. Rust and Rocket are highly capable and have a lot to offer with their functional approach, high performance, and efficient design.
Check out the Rocket’s full guide to learn more about the features it offers. Take a look at the Handlebars language guide, too, if you are interested in doing more with templates in Rocket.
To continue learning more about the Rust programming language, check out the resources linked on Rust’s learning page, which include both The Rust Book and a Rust course.
More Information
You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.
This page was originally published on