Good morning everyone and happy MonDEV ☕
Let's start a new week and we are already excited to try out a new tool, so let's dive into today's news because there's a bit to talk about.
First of all, it's been a while since I talked about Rust here in the newsletter, but we rotate through a variety of topics, so don't worry; I truly hope you find today's newsletter interesting! 🦀
Today we talk about Rocket.rs, a web framework that uses Rust as a backend language. 🚀
I waited a bit before presenting it, partly due to my doubts about the need for another framework and especially about how sensible it was to use Rust for this type of task, but a bit of curiosity, a bit of conviction that with the right task every tool can be useful, and also the fact that I remain a Rust fan, convinced me to tell you about it anyway (the idea that at some point I would like to try using this tool for the backend of my site may have also contributed, I don't deny it).
Skipping this brief introduction, instead of presenting the entire tool to you, I wanted to give you some guidance on how to start your first project smoothly, as the documentation is very comprehensive but somewhat scattered in some cases. So let's see how to set up and get a route that works with a templating engine and a route that returns a Json response.
If you don't feel like writing the code step by step and just want to enjoy reading, I've set up a repository with everything written in the next paragraphs.
First of all, you need to create a new project with cargo.
cargo new ghostylab-mondev --bin
Now navigate into the project folder and open your Cargo.toml
file. To have access to json responses and templating, add the following:
[dependencies.rocket_dyn_templates]
version = "0.2.0"
features = ["tera"]
[dependencies.rocket]
version = "0.5.1"
features = ["json"]
Also, create a templates
folder in the root directory, with a simple file index.html.tera
containing this content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{{greeting}}
</body>
</html>
Very well, now that we have some basic files, let's work on the main.rs
file.
First, import rocket in our main, the template engine, and create a route to render the template just created.
use rocket_dyn_templates::{context, Template};
#[macro_use] extern crate rocket;
#[get("/")]
fn index() -> Template {
Template::render("index",context! {greeting: "Hello World"})
}
As you can see, just like other web frameworks, we can define method and path function by function through the attribute preceding the function (in this case GET
and "/"
). The line where we return the template is very expressive; it's worth mentioning that through the context!
function, we can return an object with the variables that will be rendered in the template, and there is no need to predefine the type of this object in advance, unlike what we will see shortly with Json. Let's then add our second route.
use rocket::serde::Serialize;
use rocket::serde::json::Json;
//...
#[derive(Serialize)]
#[serde(crate = "rocket::serde")]
struct MyReturnStruct {
key:String
}
#[get("/json-res")]
fn json_res() -> Json<MyReturnStruct> {
Json(MyReturnStruct{
key:"value".to_string()
})
}
In the case of a Json response, we need to define the type we will serialize before we can return it at the call, so we need to create our own struct
or use an existing one to send a totally type-safe response. We still have one more step and we're ready:
//...
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", routes![index,json_res])
.attach(Template::fairing())
}
This is the function that starts our web server: the mount
function allows us to define all routes that start from a specific root (in this case the addresses specified for index
and json_res
will only be preceded by "/"
). Furthermore, we also start the templating system through the .attach
method.
Now you are ready, launch the cargo run
command in the terminal and you will see your routes in action; then you just have to add your own touch. The rest of the instructions to start developing are very clear in the documentation, but for this part I had to do a few more searches, so I preferred to share them directly.
Today I won't add any articles because we have already gone long enough and the week must begin. But let me know what you think of a slightly longer and more in-depth newsletter from time to time, if you like it or if maybe it's a bit too strong for a Monday morning coffee!
In the meantime, I just have to wish you a good week as always and
Happy Coding 0_1
Top comments (1)
I just learned about
tera
templates this weekend, thanks for showing the example of how Rocket uses those! Thecontext! { ... }
macro syntax is interesting