replaced AppState struct with Arc

This commit is contained in:
uh wot 2022-07-03 20:00:40 +02:00
parent 2429be10e0
commit e72779c338
Signed by: uhwot
GPG Key ID: CB2454984587B781
1 changed files with 11 additions and 12 deletions

View File

@ -2,15 +2,11 @@ use actix_web::{App, HttpResponse, HttpServer, Responder, get, post, web, middle
use actix_cors::Cors;
use serde_json::json;
use serde::Deserialize;
use std::sync::RwLock;
use std::sync::{Arc, RwLock};
mod api;
use api::{APIClient, APIError, Format};
struct AppState {
client: RwLock<APIClient>
}
#[derive(Deserialize)]
struct DeezerTrackList {
data: Vec<DeezerTrack>
@ -34,7 +30,7 @@ struct RequestParams {
}
#[post("/get_url")]
async fn get_url(req: web::Json<RequestParams>, data: web::Data<AppState>) -> impl Responder {
async fn get_url(req: web::Json<RequestParams>, state: web::Data<Arc<RwLock<APIClient>>>) -> impl Responder {
if req.formats.is_empty() {
return HttpResponse::BadRequest().body("Format list cannot be empty");
}
@ -42,7 +38,7 @@ async fn get_url(req: web::Json<RequestParams>, data: web::Data<AppState>) -> im
return HttpResponse::BadRequest().body("ID list cannot be empty");
}
let mut client = data.client.read().unwrap().clone();
let mut client = state.read().unwrap().clone();
let old_license = client.license_token.clone();
let resp: Result<DeezerTrackList, APIError> = client.api_call("song.getListData", &json!({"sng_ids":req.ids,"array_default":["SNG_ID","TRACK_TOKEN"]})).await;
@ -66,7 +62,7 @@ async fn get_url(req: web::Json<RequestParams>, data: web::Data<AppState>) -> im
};
if client.license_token != old_license {
let mut client_write = data.client.write().unwrap();
let mut client_write = state.write().unwrap();
*client_write = client;
}
@ -80,9 +76,12 @@ async fn main() -> std::io::Result<()> {
let port = std::env::var("PORT").unwrap_or("8000".to_string());
let port: u16 = port.parse().unwrap_or(8000);
let client = web::Data::new(AppState {
client: RwLock::new(APIClient::new()),
});
let bind_addr = format!("0.0.0.0:{}", port);
println!("Listening on {bind_addr}");
let client = web::Data::new(
Arc::new(RwLock::new(APIClient::new()))
);
env_logger::init();
@ -101,7 +100,7 @@ async fn main() -> std::io::Result<()> {
.service(index)
.service(get_url)
})
.bind(format!("0.0.0.0:{}", port))?
.bind(bind_addr)?
.run()
.await
}