consul_rs_plus/
session.rs1use crate::{Client};
2use std::io::Read;
3use std::fmt::Error;
4use crate::pkg::CustomError;
5
6#[derive(Serialize, Deserialize, Debug)]
7pub struct Session {
8 pub id: String,
9 pub name: String,
10 pub node: Option<String>,
11 pub LockDelay: String,
12 pub Behavior: String,
13 pub TTL: String,
14 pub node_checks: Vec<String>,
15 service_checks: Option<String>,
16 create_index: u32,
17 modify_index: u32,
18}
19
20#[derive(Debug, Serialize, Deserialize)]
21struct SessionSet {
22 ID: String,
23}
24
25impl Session {
26
27 pub fn new() -> Self {
28 Session {
29 id: "".to_string(),
30 name: "".to_string(),
31 node: None,
32 LockDelay: "".to_string(),
33 Behavior: "".to_string(),
34 TTL: "".to_string(),
35 node_checks: vec![],
36 service_checks: None,
37 create_index: 0,
38 modify_index: 0
39 }
40 }
41
42 pub fn set(&self, c: &Client, s: &Session) -> String {
43 let url = format!("http://{}:{}/v1/session/create", c.host, c.port);
44 let payload = serde_json::to_string(s).unwrap();
45 c.debug_print(format!("set session payload ------ {}", payload).as_str(), );
46 let mut rsp = reqwest::Client::new()
47 .put(&url)
48 .body(payload)
49 .send()
50 .map_err( |e| e.to_string() ).unwrap();
51 let mut body = String::new();
52 let session_set: SessionSet = rsp.json().unwrap();
55 c.debug_print(format!("session set: {:?}", session_set).as_str(), );
56 session_set.ID
57 }
58
59 pub fn renew(&self, c: &Client, sid: &str) -> Result<(), CustomError> {
60 let url = format!("http://{}:{}/v1/session/renew/{}", c.host, c.port, sid);
61 let mut rsp = reqwest::Client::new()
62 .put(&url)
63 .send()
64 .map_err( |e| e.to_string() ).unwrap();
65 let mut body = String::new();
66 rsp.read_to_string(&mut body).map_err( |e| e.to_string());
67 c.debug_print(format!("session renew: {:?}", body).as_str(), );
68 if rsp.status().is_success() {
69 Ok(())
70 } else {
71 Err(CustomError(format!("renew session err: {}", sid)))
72 }
73 }
74
75 pub fn delete(&self, c: &Client, sid: &str) -> String {
76 let url = format!("http://{}:{}/v1/session/destroy/{}", c.host, c.port, sid);
77 let mut rsp = reqwest::Client::new()
78 .put(&url)
79 .send()
80 .map_err( |e| e.to_string()).unwrap();
81 let mut body = String::new();
82 rsp.read_to_string(&mut body).map_err( |e| e.to_string() );
83 c.debug_print(format!("session delete return ---- {}", body).as_str());
84 body
85 }
86}
87
88
89
90