-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rs
94 lines (79 loc) · 2.47 KB
/
main.rs
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// ----------------------------------------------------------------
// IMPORTS
// ----------------------------------------------------------------
use actix_web::get;
use actix_web::http::header::ContentType;
use actix_web::middleware::Logger;
use actix_web::post;
use actix_web::web;
use actix_web::App;
use actix_web::HttpResponse;
use actix_web::HttpServer;
use actix_web::Responder;
use serde::Deserialize;
pub mod core;
pub mod environment;
use environment::http as env_http;
// ----------------------------------------------------------------
// MAIN
// ----------------------------------------------------------------
/// Entry method
#[tokio::main]
async fn main() -> std::io::Result<()> {
dotenv::dotenv().ok();
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
let ip = env_http::get_ip();
let port = env_http::get_port();
let result = HttpServer::new(|| {
App::new()
.wrap(Logger::default())
.wrap(Logger::new("%a %{User-Agent}i"))
.service(endpoint_ping)
.service(endpoint_token)
})
.bind((ip, port))?
.run()
.await;
return result;
}
// ----------------------------------------------------------------
// ENDPOINTS
// ----------------------------------------------------------------
#[get("/api/ping")]
async fn endpoint_ping() -> impl Responder {
return HttpResponse::Ok()
.content_type(ContentType::plaintext())
.body("success");
}
#[post("/api/token")]
async fn endpoint_token(text: web::Json<Text>) -> impl Responder {
let hash = hash_to_sha(&text.text);
let payload = Hash { hash };
return HttpResponse::Ok()
.content_type(ContentType::json())
.json(payload);
}
// ----------------------------------------------------------------
// MODELS
// ----------------------------------------------------------------
/// used to deserialise JSON payload
#[derive(Deserialize)]
struct Text {
text: String,
}
/// for serialisation of response using serde and hash as the key
#[derive(serde::Serialize)]
struct Hash {
hash: String,
}
// ----------------------------------------------------------------
// METHODS
// ----------------------------------------------------------------
/// computes sha256 hash of the string
fn hash_to_sha(text: &str) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(text);
let result = hasher.finalize();
return format!("{:x}", result);
}