feat: 首次提交

This commit is contained in:
caoqianming 2024-06-07 17:41:16 +08:00
commit 31cdb47393
4 changed files with 3205 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

3132
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

16
Cargo.toml Normal file
View File

@ -0,0 +1,16 @@
[package]
name = "hfnf_api"
version = "0.1.0"
edition = "2021"
[dependencies]
salvo = "0.67"
tokio = { version = "1", features = ["macros"] }
tracing = "0.1"
tracing-subscriber = "0.3"
sqlx = { version = "0.7", features = [ "runtime-tokio-native-tls" , "postgres", "chrono" ] }
serde = { version = "1.0.203", features = ["derive"] }
serde_json = "1.0.117"
once_cell = "1.19.0"
chrono = { version = "0.4", features = ["serde"] }
serde_with = "3.8.1"

56
src/main.rs Normal file
View File

@ -0,0 +1,56 @@
use chrono::{DateTime, Utc, FixedOffset};
use once_cell::sync::OnceCell;
use salvo::prelude::*;
use serde::{Deserialize, Serialize, Serializer};
use sqlx::{FromRow, PgPool};
static POSTGRES: OnceCell<PgPool> = OnceCell::new();
pub fn format_time_8<S>(time: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer
{
let china_timezone = FixedOffset::east_opt(8 * 3600).unwrap();
let cst_time = time.with_timezone(&china_timezone);
serializer.serialize_str(cst_time.format("%Y-%m-%d %H:%M:%S").to_string().as_str())
}
#[derive(FromRow, Serialize, Debug, Deserialize)]
pub struct Mplogx {
#[serde(serialize_with = "format_time_8")]
pub timex: DateTime<Utc>,
pub mpoint_id: String,
pub val_float: Option<f64>,
pub val_str: Option<String>
}
#[derive(Deserialize)]
pub struct MplogxQuery {
pub mpoint_id: String
}
#[inline]
fn get_postgres() -> &'static PgPool {
POSTGRES.get().unwrap()
}
#[handler]
async fn get_mplogx(req: &mut Request, res: &mut Response) {
let query:MplogxQuery = req.parse_json().await.unwrap();
let data = sqlx::query_as::<_, Mplogx>("select * from mplogx where mpoint_id = $1 order by timex desc limit 100").bind(query.mpoint_id).fetch_all(get_postgres()).await.unwrap();
res.render(serde_json::to_string(&data).unwrap());
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt().init();
let db_url = "postgresql+psycopg2://postgres:zcDsj2021@49.232.14.174:5432/hfnf";
let pool = PgPool::connect(db_url).await.unwrap();
POSTGRES.set(pool).unwrap();
let router = Router::with_path("mplogx").post(get_mplogx);
let acceptor = TcpListener::new("127.0.0.1:5800").bind().await;
Server::new(acceptor).serve(router).await;
}