monitor_common/
lib.rs

1use serde::Deserialize;
2use serde::Serialize;
3use std::net::UdpSocket;
4use std::time::{SystemTime, UNIX_EPOCH};
5
6/// 网络传输结构体
7#[derive(Serialize, Deserialize, Debug)]
8pub struct WebResult<T> {
9    pub data: Option<T>,
10    pub code: usize,
11    pub msg: Option<String>,
12}
13
14/// WebResult functions
15impl<T> WebResult<T> {
16    pub fn success(data: T) -> WebResult<T> {
17        let result: WebResult<T> = WebResult {
18            data: Some(data),
19            code: 200,
20            msg: Some("success".to_string()),
21        };
22        result
23    }
24    pub fn error(msg: String) -> WebResult<String> {
25        let result: WebResult<String> = WebResult {
26            data: None,
27            code: 503,
28            msg: Some(msg),
29        };
30        result
31    }
32}
33
34/// 获取本机IP
35pub fn get_local_ip() -> String {
36    let socket = UdpSocket::bind("0.0.0.0:0").unwrap();
37    socket.connect("8.8.8.8:80").unwrap();
38    socket.local_addr().unwrap().ip().to_string()
39}
40
41/// 获取时间戳
42/// > 精确到秒,非毫秒
43pub async fn get_timestamp() -> u64 {
44    let start = SystemTime::now();
45    let since_the_epoch = start
46        .duration_since(UNIX_EPOCH)
47        .expect("Time went backwards");
48    let timestamp = since_the_epoch.as_secs();
49    timestamp
50}
51
52/// Get deploy time line
53pub async fn get_time_line() -> u64 {
54    let timestamp = get_timestamp().await;
55    let time_line = timestamp - 2 * 3600;
56    time_line
57}