1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
use std::{
env::args,
io::{stdin, stdout, IsTerminal},
};
use actix_web::{
get, http::header::ContentType, post, web, App, HttpResponse, HttpServer, Responder,
};
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
struct Registration {
url: String,
}
#[post("/register")]
async fn register(registration: web::Json<Registration>) -> impl Responder {
HttpResponse::Ok()
.content_type(ContentType::json())
.body(serde_json::to_string(®istration).unwrap())
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(register))
.bind(("127.0.0.1", 8080))?
.run()
.await
}
#[cfg(test)]
mod app_tests {
use actix_web::{body, http::header::ContentType, test, App};
use super::*;
#[actix_web::test]
async fn post_registration_echoes_back_registration_data_with_unique_id() {
let app = test::init_service(App::new().service(register)).await;
let registration = Registration {
url: "http://192.168.1.1".to_string(),
};
let req = test::TestRequest::post()
.uri("/register")
.set_json(registration.clone())
.insert_header(ContentType::json())
.to_request();
let resp = test::call_service(&app, req).await;
assert!(resp.status().is_success());
let body = resp.into_body();
let bytes = body::to_bytes(body).await;
assert_eq!(
registration,
serde_json::from_slice(&bytes.unwrap()).unwrap()
);
}
}
|