SeaBattle/sea_battle_backend/src/server.rs

67 lines
1.9 KiB
Rust
Raw Normal View History

2022-09-14 14:50:29 +00:00
use actix_cors::Cors;
use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer, Responder};
use actix_web_actors::ws;
2022-09-17 10:02:13 +00:00
use crate::args::Args;
use crate::data::{GameRules, PlayConfiguration};
use crate::human_player_ws::{HumanPlayerWS, StartMode};
2022-09-14 14:50:29 +00:00
/// The default '/' route
async fn index() -> impl Responder {
HttpResponse::Ok().json("Sea battle backend")
}
/// The default 404 route
async fn not_found() -> impl Responder {
HttpResponse::NotFound().json("You missed your strike lol")
}
/// Get bot configuration
async fn game_configuration() -> impl Responder {
HttpResponse::Ok().json(PlayConfiguration::default())
}
/// Start bot game
async fn start_bot_play(
req: HttpRequest,
stream: web::Payload,
query: web::Query<GameRules>,
) -> Result<HttpResponse, actix_web::Error> {
let errors = query.0.get_errors();
if !errors.is_empty() {
return Ok(HttpResponse::BadRequest().json(errors));
}
let mut player_ws = HumanPlayerWS::default();
player_ws.start_mode = StartMode::Bot(query.0.clone());
let resp = ws::start(player_ws, &req, stream);
log::info!("New bot play with configuration: {:?}", &query.0);
resp
}
2022-09-14 15:36:16 +00:00
pub async fn start_server(args: Args) -> std::io::Result<()> {
2022-09-14 14:50:29 +00:00
let args_clone = args.clone();
HttpServer::new(move || {
let mut cors = Cors::default();
match args_clone.cors.as_deref() {
Some("*") => cors = cors.allow_any_origin(),
Some(orig) => cors = cors.allowed_origin(orig),
None => {}
}
App::new()
.wrap(cors)
.route("/config", web::get().to(game_configuration))
.route("/play/bot", web::get().to(start_bot_play))
2022-09-17 10:02:13 +00:00
// TODO : create & accept invite
// TODO : join random
2022-09-14 14:50:29 +00:00
.route("/", web::get().to(index))
.route("{tail:.*}", web::get().to(not_found))
})
.bind(&args.listen_address)?
.run()
.await
}