//! server.rs

use crate::Router;
use hyper::server::Server;
use hyper::service::{make_service_fn, service_fn};
use std::net::SocketAddr;
use std::sync::Arc;

impl Router {
	/// 启动 HTTP 服务器
	pub async fn run(self, host: &str, port: u16) {
		let addr: SocketAddr = format!("{}:{}", host, port).parse().expect("invalid socket address: invalid IP address syntax");

		let router = Arc::new(self);

		let make_svc = make_service_fn(move |_conn| {
			let router = router.clone();
			async move {
				Ok::<_, hyper::Error>(service_fn(move |req| {
					let router = router.clone();
					async move { Ok::<_, hyper::Error>(router.handle_request(req).await) }
				}))
			}
		});

		let server = Server::bind(&addr).serve(make_svc);

		println!("Nimble server running on http://{}", addr);
		println!("Press Ctrl+C to stop");

		if let Err(e) = server.await {
			eprintln!("Server error: {}", e);
		}
	}
}
