En este tutorial aprenderemos a escribir código de Rust en un framework backend llamado Salvo.rs
¿Qué es salvo.rs?
Salvo.rs es un framework de Rust que permite crear aplicaciones web backend.
Entre sus caracteristicas estan:
Basado en Hyper y Tokio. Basicamente tokio maneja código aincrono, Hyper esta encima creando un servidor web, y encima esta salvo, creando rutas.
Soporte a Http1, Http2 y Http3
Soporta WebSocket
Genera SSL automatico
Creación de Proyecto
cargo new salvo_tutorial --bin
cd salvo_tutorial
cargo init
actualiza cargo.toml
[dependencies]
salvo = "*"
tokio = { version = "1", features = ["macros"] }
o tambien puede ser esto:
tokio = { version = "1", features = ["full"] }
src/main.rs:
use salvo::prelude::*;
#[handler]
async fn hello_world() -> &'static str {
"Hello, world!"
}
#[tokio::main]
async fn main() {
let router = Router::new().get(hello_world);
Server::new(TcpListener::bind("127.0.0.1:3000"))
.serve(router)
.await;
}
cargo run
Luego puedes visitar: http://localhost:3000/
Multiple Routes
#[handler]
async fn home() -> &'static str {
"home page!"
}
#[handler]
async fn about() -> &'static str {
"about!"
}
#[handler]
async fn services() -> &'static str {
"services!"
}
#[tokio::main]
async fn main() {
let router = Router::new()
.push(Router::new().path("").get(home))
.push(Router::new().path("about").get(about))
.push(Router::new().path("services").get(services));
Server::new(TcpListener::bind("127.0.0.1:3000"))
.serve(router)
.await;
}
Static Files
crea una carpeta public/index.html, con lo siguiente:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Salvo.rs</title>
<link rel="stylesheet" href="./main.css">
</head>
<body>
<h1>Salvo rs tutorial</h1>
<script src="./main.js"></script>
</body>
</html>
Luego actualiza el archivo cargo.toml
salvo = { version = "*", features = ["serve-static"] }
y finalmente el archivo main.rs:
use salvo::{prelude::*, serve_static::StaticDir};
#[handler]
async fn hello_world() -> &'static str {
"Hello, world!"
}
#[tokio::main]
async fn main() {
let router = Router::with_path("<**path>").get(
StaticDir::new(["public"])
.with_defaults("index.html")
.with_listing(true),
);
Server::new(TcpListener::bind("127.0.0.1:3000"))
.serve(router)
.await;
}
cargo run
Con este codigo ya puedes cargar todos los archivo que esten en la carpeta public, ya sea imagenes, javascript css, o cualquier otro archivo.
Tambien puedes cargos archivos directos como /index.html, /index.css y asi.
Tambien hay otra funcion llmada StaticFile que como su nombre indica permite cargar un archivo individual y servirlo al cliente
Routas y archivos estaticos
let router = Router::new()
.push(Router::new().path("").get(home))
.push(Router::new().path("about").get(about))
.push(Router::new().path("services").get(services))
.push(
Router::with_path("<**path>").get(
StaticDir::new(["public"])
.with_defaults("index.html")
.with_listing(true),
),
);
Middlewares
Los middlewares son funciones que se ejecutan antes de que se ejecute la logica de una ruta. Salvo tiene varios middlewares
.hoop(Compression::new().with_algos(&[CompressionAlgo::Gzip]))
SPA
use rust_embed::RustEmbed;
use salvo::{prelude::*, serve_static::static_embed};
#[derive(RustEmbed)]
#[folder = "client/dist"]
struct Assets;
#[tokio::main]
async fn main() {
let router =
Router::with_path("<**path>").get(static_embed::<Assets>().with_fallback("index.html"));
Server::new(TcpListener::bind("127.0.0.1:3000"))
.serve(router)
.await;
}
- https://salvo.rs/book/middlewares/serve-static.html#main-features
- https://github.com/pyrossh/rust-embed
Más Recursos
https://salvo.rs/book/middlewares/logging.html https://salvo.rs/book/middlewares/compression.html#sample-code