@sebasmagri - May, 2017
Application Programmer Interface
+
Protocols and Technologies you can use when building apps for the Web
Data
struct LoadAvg {
last1: f64,
last5: f64,
last15: f64
}
...
let load_avg = LoadAvg {
last1: 0.36,
last5: 0.71,
last15: 1.1
}
...
println!("{}", load_avg.last1)
enum Gender {
Male,
Female,
Other
}
...
struct Person {
name: String,
age: i32,
gender: Gender
}
...
let p = Person {
name: "Sebastián".to_string(),
age: 15,
gender: Gender::Male
}
Type descriptions
Multiple options types
Safety
Ownership | Borrowing | Lifetimes |
---|
Rust provides mechanisms to handle memory safely in an automatic fashion.
Ownership and Lifetimes
Principles of the ownership system
Borrowing
Principles of the borrow checker(TM)
AKA: The ownership cop
A Web Framework for Rust, focused on simplicity, performance, flexibility and safe data handling.
https://rocket.rs/
Rocket uses data attributes to indicate which functions handle specific requests.
These attributes allow the definition of the request method, the route and response content type.
#[get("/")]
fn home() -> String { ... }
#[post("/news", data = "<entry>")]
fn new(entry: Entry) -> String { ... }
#[head("/news")]
fn head() -> String { ... }
#[get("/news")]
fn entries() -> String { ... }
#[get("/news/<id>")]
fn entrie(id: i32) -> String { ... }
#[put("/news/<id>", data = "<entry>")]
fn update(entry: Entry) -> String { ... }
#[patch("/news/<id>", data = "<entry>")]
fn update_partial(id: i32, entry: Entry) -> ...
#[route(OPTIONS, "/news")]
fn options() -> String { ... }
Handles will get requests that match all the given preconditions and will generate a response for clients based on the given parameters.
#[get("/")]
fn hello() -> String {
"Hello World".to_string()
}
// URL path parameters
#[get("/<name>")]
fn home(name: &str) -> String {
format!("Hello {}!", name)
}
// Body parameters
#[post("/login", data = "<user_form>")]
fn login(user_form: Form<UserLogin>) -> String {
// Use `user_form`, return a String.
}
// ## Request Guards
// Request requirements
#[get("/sensitive")]
fn sensitive(key: APIKey) -> &'static str { ... }
Responder is a trait provided by Rocket that will convert the handler's return data type into a HTTP response.
struct SystemLoad {
last1: f32,
last5: f32,
last15: f32
}
impl<'r, R: Responder<'r>> Responder<'r> for SystemLoad { ... }
#[get("/")]
fn hello() -> T {
"Hello World".to_string()
}
In the boot up process, Rocket is going to mount the routes it should handle and it's going to start a Web Server ready to get requests.
rocket::ignite()
.mount("/base", routes![index, another])
.launch()
...
🚀 Rocket has launched from http://localhost:8000...
- Workshop repo: https://github.com/sebasmagri/rocket-loadavg-api
- The Rust Book: https://doc.rust-lang.org/stable/book/
- Crates docs: https://docs.rs/
- Rocket's Guide: https://rocket.rs/guide
- Rocket's Examples: https://github.com/SergioBenitez/Rocket
- Rocket's IRC channel: #rocket@irc.mozilla.org
Be nice to each other.