5 use std
::collections
::HashMap
;
6 use lazy_static
::lazy_static
;
8 //use apitest::json_schema::*;
9 use apitest
::api_info
::*;
11 //use serde_derive::{Serialize, Deserialize};
12 use serde_json
::{json, Value}
;
14 use url
::form_urlencoded
;
16 use hyper
::{Method, Body, Request, Response, Server, StatusCode}
;
17 use hyper
::rt
::Future
;
18 use hyper
::service
::service_fn_ok
;
20 macro_rules
! http_error
{
21 ($status
:ident
, $msg
:expr
) => {{
22 let mut resp
= Response
::new(Body
::from($msg
));
23 *resp
.status_mut() = StatusCode
::$status
;
28 fn parse_query(query
: &str) -> Value
{
30 println
!("PARSE QUERY {}", query
);
32 // fixme: what about repeated parameters (arrays?)
33 let mut raw_param
= HashMap
::new();
34 for (k
, v
) in form_urlencoded
::parse(query
.as_bytes()) {
35 println
!("QUERY PARAM {} value {}", k
, v
);
36 raw_param
.insert(k
, v
);
38 println
!("QUERY HASH {:?}", raw_param
);
43 fn handle_request(req
: Request
<Body
>) -> Response
<Body
> {
45 let method
= req
.method();
46 let path
= req
.uri().path();
47 let query
= req
.uri().query();
48 let components
: Vec
<&str> = path
.split('
/'
).filter(|x
| !x
.is_empty()).collect();
49 let comp_len
= components
.len();
51 println
!("REQUEST {} {}", method
, path
);
52 println
!("COMPO {:?}", components
);
54 if comp_len
>= 1 && components
[0] == "api3" {
55 println
!("GOT API REQUEST");
57 let format
= components
[1];
59 http_error
!(NOT_FOUND
, format
!("Unsupported format '{}'\n", format
))
62 if let Some(info
) = API_ROOT
.find_method(&components
[2..]) {
63 println
!("FOUND INFO");
64 let api_method_opt
= match method
{
65 &Method
::GET
=> info
.get
,
66 &Method
::PUT
=> info
.put
,
67 &Method
::POST
=> info
.post
,
68 &Method
::DELETE
=> info
.delete
,
71 let api_method
= match api_method_opt
{
73 _
=> http_error
!(NOT_FOUND
, format
!("No such method '{} {}'\n", method
, path
)),
79 let param
= match query
{
80 Some(data
) => parse_query(data
),
84 match (api_method
.handler
)(param
) {
86 let json_str
= res
.to_string();
87 return Response
::new(Body
::from(json_str
));
90 http_error
!(NOT_FOUND
, format
!("Method returned error '{}'\n", err
));
95 http_error
!(NOT_FOUND
, format
!("No such path '{}'\n", path
));
100 Response
::new(Body
::from("RETURN WEB GUI\n"))
104 static ref API_ROOT
: MethodInfo
= apitest
::api3
::get_api_definition();
108 println
!("Fast Static Type Definitions 1");
110 let addr
= ([127, 0, 0, 1], 8007).into();
113 // service_fn_ok converts our function into a `Service`
114 service_fn_ok(handle_request
)
117 let server
= Server
::bind(&addr
)
119 .map_err(|e
| eprintln
!("server error: {}", e
));
121 // Run this server for... forever!
122 hyper
::rt
::run(server
);