Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // webserver on rust using tide async-std and serde
- //
- // [dependencies]
- // tide = "0.16.0"
- // async-std = { version = "1.6.0", features = ["attributes"] }
- // serde = { version = "1.0", features = ["derive"]
- //
- use tide::Request;
- //use tide::Response;
- //use tide::Result;
- //use tide::StatusCode;
- use tide::prelude::*;
- use serde::{Deserialize, Serialize};
- use std::collections::HashMap;
- use std::collections::hash_map::{Entry};
- use std::sync::{Arc, RwLock};
- #[derive(Serialize, Deserialize)]
- struct Animal {
- name: String,
- age: u8,
- }
- #[derive(Hash, Eq, PartialEq, Clone, Debug, Deserialize, Serialize)]
- struct Dino {
- name: String,
- weight: u16,
- diet: String
- }
- #[derive(Clone, Debug, Deserialize, Serialize)]
- struct State {
- dinos: Arc<RwLock<HashMap<String, Dino>>>
- }
- #[derive(Debug, Deserialize)]
- struct QueryObj {
- id: String,
- name: String,
- }
- #[derive(Debug, Deserialize, Serialize)]
- struct Counter {
- count: usize,
- }
- #[derive(Debug, Deserialize)]
- struct Order {
- name: String,
- shoes: u16,
- }
- #[async_std::main]
- async fn main() -> Result<(), std::io::Error> {
- //async fn main() -> Result<()> {
- tide::log::start();
- let state = State {
- dinos: Default::default()
- };
- //let mut app = tide::new();
- let mut app = tide::with_state(state);
- // curl -i 'localhost:8080'
- // server replies with hello world
- //
- app.at("/").get(|_| async { Ok("Hello, world!") });
- // curl -i -H "Acceptication/json" -d '{ "count": 41 }' -X GET localhost:8080/counter
- // returns HTML with the count supplied incremented by 1 unit
- //
- app.at("/counter").get(|mut req: tide::Request<State>| async move {
- let mut counter: Counter = req.body_json().await.unwrap();
- println!("count is {}", counter.count);
- counter.count += 1;
- //tide::Response::new(200).body_json(&counter).unwrap()
- Ok(tide::Response::builder(200)
- .body(format!("<html><h2>New Count is :-, {}!</h2></html>",
- counter.count))
- .header("Server", "tide")
- .content_type(tide::http::mime::HTML)
- .build())
- });
- // curl -i 'localhost:8080/nicko'
- // returns the htm using the variable as nicko in the example
- //
- app.at("/:user").get(|req: tide::Request<State>| async move {
- Ok(tide::Response::builder(200)
- .body(format!("<html><h2>Hello, {}!</h2></html>",
- req.param("user")?))
- .header("Server", "tide")
- .content_type(tide::http::mime::HTML)
- .build())
- });
- // curl -i 'localhost:8080/index'
- // returns the html page index.html
- //
- app.at("/index").serve_file("index.html")?;
- // curl -i 'localhost:8080/animals'
- // returns the hardcoded json as below
- //
- app.at("/animals").get(|_| async {
- let animals = vec![
- Animal { name: "nick".into(), age: 8 },
- Animal { name: "paul".into(), age: 3 },
- ];
- Ok(tide::Body::from_json(&animals)?)
- });
- // curl -X POST -H "Content-Type: application/json" -d '{"name":"nick","age":19}' localhost:8080/animal
- // returns the animal names sent as a json message
- //
- app.at("/animal").post(|mut req: tide::Request<State>| async move {
- let animal: Animal = req.body_json().await?;
- Ok(tide::Body::from_json(&animal)?)
- });
- // curl -d '{"name":"dinodino", "weight": 50, "diet":"carnivorous"}' http://localhost:8080/dinos
- // returns the json sent as a json message
- //
- app.at("/dinos").post(|mut req: tide::Request<State>| async move {
- let dino: Dino = req.body_json().await?;
- println!("{:?}", dino);
- let mut dinos = req.state().dinos.write();
- let mut hash_dino: HashMap<String, Dino> = HashMap::new();
- hash_dino.insert(String::from(&dino.name), dino.clone());
- let dinos = hash_dino;
- let mut res = tide::Response::new(201);
- res.set_body(tide::Body::from_json(&dino)?);
- Ok(res)
- });
- // curl --dump-header - localhost:8080/hashmapsearch/<name> e.g. <name>=mark
- // responds with the number associated with the name specified as <name>
- //
- app.at("/hashmapsearch/:name")
- .get(|req: Request<State>| async move {
- let key: String = req.param("name").unwrap().to_string();
- let mut hash_map: HashMap<String, i32> = HashMap::new();
- hash_map.insert(String::from("mark"), 82);
- hash_map.insert(String::from("nicholas"), 76);
- hash_map.insert(String::from("anton"), 67);
- hash_map.insert(String::from("ellis"), 2);
- hash_map.insert(String::from("dee"), 11);
- hash_map.insert(String::from("eamon"), 99);
- hash_map.insert(String::from("jock"), 14);
- hash_map.insert(String::from("iain"), 83);
- let res = match hash_map.entry(key) {
- Entry::Vacant(_entry) => tide::Response::new(404),
- Entry::Occupied(entry) => {
- let mut res = tide::Response::new(200);
- res.set_body(tide::Body::from_json(&entry.get())?);
- res
- }
- };
- Ok(res)
- });
- // curl -i 'localhost:8080/users?id=1&name=mark'
- // returns the name and id sent as a html page message
- //
- app.at("/users").get(|req: Request<State>| {
- async move {
- let user_id = req.query::<QueryObj>().unwrap();
- Ok(tide::Response::builder(200)
- .body(format!("<html><h2>Hello, {} your id was {}!</h2></html>",
- user_id.name, user_id.id))
- .header("Server", "tide")
- .content_type(tide::http::mime::HTML)
- .build())
- }
- });
- // curl --dump-header - localhost:8080/hc
- // curl --dump-header - localhost:8080/hc/json
- // prints the parsed route back to the client
- //
- app.at("/hc")
- .get(|_| async move { Ok("ok hc!") })
- .at("/json")
- .get(|_| async move { Ok("ok json!") });
- // curl localhost:8080/orders/shoes -d '{ "name": "Thom", "shoes": 4 }'
- //
- app.at("/orders/shoes").post(order_shoes);
- app.listen("127.0.0.1:8080").await?;
- Ok(())
- }
- async fn order_shoes(mut req: Request<State>) -> tide::Result {
- let Order { name, shoes } = req.body_json().await?;
- Ok(format!("Hello, {}! I've put in an order for {} shoes", name, shoes).into())
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement