2

Is Rust ready for the web yet?

 1 year ago
source link: https://blog.devgenius.io/is-rust-ready-for-the-web-yet-9ec38c01dcaf
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

TECH BUILD

Is Rust ready for the web yet?

Rust has matured for 5 years. But is it ready to build web applications?

Rust programming language — are they web yet?

Photo by Zsolt Palatinus on Unsplash

Why use rust?

“Given our dependence on Rust, we need deep in-house Rust expertise, just as we have with Java and other foundational technologies,” said Matt Asay, an open-source exec at AWS.

Having his first stable release on 15 May 2015 Rust is a relatively new programming language. Rust has a similar syntax to C++ but can guarantee memory safety by using a borrow checker to validate references. Which means that it doesn't need a garbage collection.

The growing popularity of Rust is also notable. Since 2016 Rust is voted every year, in the StackOverflow developer survey, as the “most loved programming language”¹. Rust, has quickly established a fanbase at Microsoft, Amazon Web Services (AWS), and other tech companies.

There are many signs that Rust is here to stay and help us create better software and products. But is it ready to create web apps?

Building an API with Rust

In their webpage, Rust says that it comes with the command line, web assembly, networking, and embed built-in. In this article, I will stick with the networking part. We will build an example of a simple API with a “Hello World” JSON response.

First, we need to install Rust and for that. We will follow the Rust recommended rustup. To install Rust just run the following command in your shell. Ignore if you already have!

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

To build a web server and after some research, I choose to use the “actix” framework. Actix is a powerful, pragmatic, and extremely fast web framework for Rust. Given this description looks like it may solve our problem (build an API). Create a new project with cargo is pretty straight forward:

cargo new myapp
cd myapp

In your project directory, you should have a Cargo.toml. This file is like the composer.json for PHP. It is a manifest where you can describe the project dependencies among other things. Go to your Cargo.toml file and add the actix dependency:

[dependencies]
actix-web = "3"

Just to check if everything is OK and the web serves responds to our requests let's print the classic “hello-world” on a web page:

use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};

#[get("/")]
async fn hello() -> impl Responder {
HttpResponse::Ok().body("Hello world!")
}#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(hello)
})
.bind("127.0.0.1:8080")?
.run()
.await
}

Got to your terminal in the project directory and hit: cargo run.

This command will download all the dependencies and compile the code into a binary file. The app will be running on port 8080 waiting for requests to arrive. If you go to 127.0.0.1:8080 you will see “Hello world!” on your web browser.

Our web server is working. Now, as I said before let’s get a JSON response with the same message. To work with JSON we need an extra dependency. Serde allows serializing and deserializing Rust data structures efficiently and generically. In your Cargo.toml append to the new dependency:

serde = “1.0.118”

The next step is to change our hello method to respond with a JSON instead of plain text:

use actix_web::{get, App, HttpResponse, HttpServer, Responder};
use serde::{Deserialize, Serialize};#[derive(Serialize, Deserialize)]
struct MyObj {
message: String,
}#[get("/")]
async fn hello() -> impl Responder {
HttpResponse::Ok().json(MyObj {
message: String::from("Hello, world!"),
})
}#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(hello)
})
.bind("127.0.0.1:8080")?
.run()
.await
}

Here we declare the JSON (MyObj) structure that will be returned and in the response, we compose the JSON. The main remains the same as it is only responsible for route and print the response given by the method hello.

Conclusion

This is a pretty basic example and not challenging at all. It doesn't prove that Rust is suitable for web development. But I believe that has the requirements to build web apps. I know a few startups that are now shifting some services, previously written in other languages (PHP, node, etc), to newer languages like Rust. Getting started is easy. Because of the documentation and the fact that is a compiled language and is memory safe can make it a great tool to develop all sorts of software in the future.

Next time I will try to make a real web app. Like a to-do list or something similar, using a database, post and get requests. All that stuff that is required to build a web app. Working with Rust is fun and will do it more often in the future in my projects and I am excited to learn even more.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK