Advertisement
aircampro

rust tide and atomic webserver

Nov 14th, 2023 (edited)
2,221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 3.99 KB | Software | 0 0
  1. // In this example we store an atomic value on the tide webserver
  2. // it is controlled by requests from the clients
  3. //
  4. use tide::Request;
  5. use tide::prelude::*;
  6. use std::sync::{Arc};
  7. use std::sync::atomic::{AtomicI32, Ordering};
  8.  
  9. // the counter can be +ve or -ve so its an integer 32
  10. #[derive(Clone)]
  11. struct State {
  12.     value: Arc<AtomicI32>,
  13. }
  14.  
  15. impl State {
  16.     fn new() -> Self {
  17.         Self {
  18.             value: Arc::new(AtomicI32::new(0)),
  19.         }
  20.     }
  21. }
  22.  
  23. // we define value to add/set sent from the client can only be positive as a u16
  24. #[derive(Debug, Deserialize)]
  25. struct QueryObj {
  26.     value: Option<u16>,
  27.     set_by: String,
  28. }
  29.  
  30. impl QueryObj {
  31.     /// Create a new QueryObj.
  32.     fn new(value: Option<u16>, set_by: &str) -> QueryObj {
  33.         QueryObj { value: value, set_by: set_by.to_string() }
  34.     }
  35.     fn get_id(&self) -> &str {
  36.         &self.set_by
  37.     }
  38.     fn get_val(&self) -> i32 {
  39.         self.value.unwrap_or(0) as i32
  40.     }
  41. }
  42.  
  43. #[async_std::main]
  44. async fn main() -> tide::Result<()> {
  45.     let mut app = tide::with_state(State::new());
  46.     app.with(tide::log::LogMiddleware::new());
  47.     // curl -i 'localhost:8080/add
  48.     // returns the saved atomic value to the client
  49.     //
  50.     app.at("/").get(|req: tide::Request<State>| async move {
  51.         let state = req.state();
  52.         let value = state.value.load(Ordering::Relaxed);
  53.         Ok(format!("{}\n", value))
  54.     });
  55.     // curl -i 'localhost:8080/add
  56.     // increments the atomic value
  57.     //
  58.     app.at("/inc").get(|req: tide::Request<State>| async move {
  59.         let state = req.state();
  60.         let value = state.value.fetch_add(1, Ordering::Relaxed) + 1;
  61.         Ok(format!("{}\n", value))
  62.     });
  63.     // curl -i 'localhost:8080/sub
  64.     // subtracts from the atomic value
  65.     //
  66.     app.at("/sub").get(|req: tide::Request<State>| async move {
  67.         let state = req.state();
  68.         let value = state.value.fetch_sub(1, Ordering::Relaxed) - 1;
  69.         Ok(format!("{}\n", value))
  70.     });
  71.     // curl -i 'localhost:8080/add?value=100&set_by=charlie'
  72.     // adds to the atomic memory value to what is specified in the curl
  73.     //
  74.     app.at("/add").get(|req: Request<State>| {
  75.         async move {
  76.            let client_data = req.query::<QueryObj>().unwrap();
  77.            let state = req.state();
  78.            let value = state.value.fetch_add(client_data.get_val(),Ordering::Relaxed) + 1;
  79.            Ok(tide::Response::builder(200)
  80.                .body(format!("<html><h2>New Value set to {} by user {}!</h2></html>",
  81.                 client_data.get_val(), client_data.get_id()))
  82.                .header("Server", "tide")
  83.                .content_type(tide::http::mime::HTML)
  84.                .build())
  85.         }
  86.     });
  87.     // curl -i 'localhost:8080/reset
  88.     // sets the atomic memory value to zero
  89.     //
  90.     app.at("/reset").get(|req: tide::Request<State>| async move {
  91.         let state = req.state();
  92.         let value = state.value.load(Ordering::Relaxed);
  93.         let value = state.value.fetch_sub(value, Ordering::Relaxed);           
  94.         Ok(format!("{}\n", value))
  95.     });
  96.     // curl -i 'localhost:8080/set?value=900&set_by=rocksy'
  97.     // sets the atomic memory value to what is specified in the curl
  98.     //
  99.     app.at("/set").get(|req: Request<State>| {
  100.         async move {
  101.            let client_data = req.query::<QueryObj>().unwrap();
  102.            let state = req.state();
  103.            let value = state.value.load(Ordering::Relaxed);
  104.            let value = state.value.fetch_sub(value, Ordering::Relaxed);          
  105.            let value = state.value.fetch_add(client_data.get_val(),Ordering::Relaxed) + 1;
  106.            Ok(tide::Response::builder(200)
  107.                .body(format!("<html><h2>New Value set to {} by user {}!</h2></html>",
  108.                 client_data.get_val(), client_data.get_id()))
  109.                .header("Server", "tide")
  110.                .content_type(tide::http::mime::HTML)
  111.                .build())
  112.         }
  113.     });
  114.     app.listen("127.0.0.1:8080").await?;
  115.     Ok(())
  116. }
  117.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement