1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
use reqwest::{Response, Client, Url, UrlError, Error as ReqError};
use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;
use super::gameserver::Token;
pub struct BackendConnection {
host: String,
req_sender: Sender<RequestData>,
res_rec: Receiver<ResponseResult>,
}
#[derive(Debug)]
pub enum BackendError {
UrlError(UrlError),
RequestError(ReqError),
InvalidTokenFormat,
InvalidToken,
}
pub type TokenValidity = Result<(), BackendError>;
pub type RequestData = Url;
pub type ResponseResult = Result<Response, ReqError>;
impl BackendConnection {
fn run_background(req_rec: Receiver<RequestData>, res_sender: Sender<ResponseResult>) {
let client = Client::new();
loop {
let request_data = req_rec.recv().unwrap();
let location = request_data;
let request = client.get(location);
let response = request.send();
res_sender.send(response).unwrap();
}
}
pub fn new(host: &str) -> Self {
let (req_sender, req_rec): (Sender<RequestData>, Receiver<RequestData>)
= mpsc::channel();
let (res_sender, res_rec): (Sender<ResponseResult>, Receiver<ResponseResult>)
= mpsc::channel();
std::thread::spawn(move || Self::run_background(req_rec, res_sender));
BackendConnection {
host: host.to_string(),
req_sender,
res_rec,
}
}
pub fn request(&self, location: &str) -> Result<(), UrlError> {
Ok(self.req_sender.send(Url::parse(&format!("{}{}", self.host, location))?).unwrap())
}
pub fn get_response(&self) -> ResponseResult {
self.res_rec.recv().unwrap()
}
pub fn host_name<'a>(&'a self) -> &'a str {
&self.host
}
pub fn validate_token(&self, token: &Token) -> TokenValidity {
let location = format!("/api/lobby/tokens/{}", token);
self.request(&location).map_err(|err| BackendError::UrlError(err))?;
let response = self.get_response();
println!("backend response: {:?}", response);
Ok(())
}
}
|