Skip to content

Instantly share code, notes, and snippets.

@wdonet
Created August 3, 2019 04:59
Show Gist options
  • Select an option

  • Save wdonet/6e1cec251439f27aacb89e61599cbb85 to your computer and use it in GitHub Desktop.

Select an option

Save wdonet/6e1cec251439f27aacb89e61599cbb85 to your computer and use it in GitHub Desktop.
Rocket snippet for a short talk of how to use Rocket
Rocket
Intro
- Primitives to build web servers
- Routing (params and handlers)
- Validation
- Error Handling
- Pre-Processing of requests
- Post-processing of responses
Setup Rust
curl https://sh.rustup.rs -sSf | sh
or windows
- rustup show
- rustup update && cargo update
- rustup override set nightly (at the project dir)
Setup Rocket
- cargo new hello-rocket --bin
- cd hello-rocket
- rocket = “0.4.1”
First Hello World
- Code
#![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();
}
- Add more endpoints GET and POST
curl -d "param=ok" -X POST http://localhost:8000/app/postSmt
- Modules and namespace
mod other {
pub fn test() -> &’static str {“X”}
}
Rocket::ignite().mount(“/“, routes![other::test]);
- API
// #![feature(plugin)]
// #![plugin(rocket_codegen)]
#[derive(Debug)]
struct LoadAvg {
last: f64, // last minute load average
last5: f64, // last 5 minutes load average
last15: f64 // last 15 minutes load average
}
impl LoadAvg {
fn new() -> LoadAvg {
// Placeholder
LoadAvg {
last: 0.9,
last5: 1.5,
last15: 1.8
}
}
}
main()
let load_avg = LoadAvg::new();
println!("{:?}", load_avg);
- JSON
[dependencies]
rocket_contrib = { version = "0.4.1", features = ["json"] }
serde = "1.0.91"
serde_json = "1.0.39"
serde_derive = "1.0.91"
extern crate serde_json;
#[macro_use] extern crate rocket_contrib;
#[macro_use] extern crate serde_derive;
use rocket_contrib::JSON;
#[derive(Serialize)]
struct LoadAvg {}
#[get("/loadavg")]
fn loadavg() -> JSON<LoadAvg> {
JSON(LoadAvg::new())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment