xref: /xiu/protocol/httpflv/src/server.rs (revision 5377b641)
1 // use super::errors::ServerError;
2 use hyper::service::{make_service_fn, service_fn};
3 use hyper::{header, Body, Client, Method, Request, Response, Server, StatusCode};
4 type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
5 
6 type GenericError = Box<dyn std::error::Error + Send + Sync>;
7 
8 static INDEX: &[u8] = b"<a href=\"test.html\">test.html</a>";
9 static INTERNAL_SERVER_ERROR: &[u8] = b"Internal Server Error";
10 static NOTFOUND: &[u8] = b"Not Found";
11 static POST_DATA: &str = r#"{"original": "data"}"#;
12 static URL: &str = "http://127.0.0.1:1337/json_api";
13 
14 pub struct HttpFlvServer {
15     port: u32,
16 }
17 
18 impl HttpFlvServer {
19     pub fn new(port: u32) -> Self {
20         Self { port: port }
21     }
22 
23     async fn api_get_response(&mut self) -> Result<Response<Body>, Error> {
24         let data = vec!["foo", "bar"];
25         let res = match serde_json::to_string(&data) {
26             Ok(json) => Response::builder()
27                 .header(header::CONTENT_TYPE, "application/json")
28                 .body(Body::from(json))
29                 .unwrap(),
30             Err(_) => Response::builder()
31                 .status(StatusCode::INTERNAL_SERVER_ERROR)
32                 .body(INTERNAL_SERVER_ERROR.into())
33                 .unwrap(),
34         };
35         Ok(res)
36     }
37 
38     async fn route(&'static mut self, req: Request<Body>) -> Result<Response<Body>, Error> {
39         match (req.method(), req.uri().path()) {
40             (&Method::GET, "/json_api") => self.api_get_response().await,
41             _ => {
42                 // Return 404 not found response.
43                 Ok(Response::builder()
44                     .status(StatusCode::NOT_FOUND)
45                     .body(NOTFOUND.into())
46                     .unwrap())
47             }
48         }
49     }
50 
51     pub async fn run(&'static mut self) {
52         let new_service = make_service_fn(move |_| {
53             // Move a clone of `client` into the `service_fn`.
54 
55             async {
56                 Ok::<_, GenericError>(service_fn(move | req| {
57                     // Clone again to ensure that client outlives this closure.
58                     self.route(req)
59                 }))
60             }
61         });
62 
63         let addr = "127.0.0.1:1337".parse().unwrap();
64         let server = Server::bind(&addr).serve(new_service);
65         println!("Listening on http://{}", addr);
66         let _ = server.await;
67     }
68 }
69