Guest User

Untitled

a guest
Oct 24th, 2022
16
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.26 KB | None | 0 0
  1. use once_cell::sync::OnceCell;
  2. use salvo::prelude::*;
  3. use serde::Serialize;
  4. use sqlx::{FromRow, PgPool};
  5.  
  6. static POSTGRES: OnceCell<PgPool> = OnceCell::new();
  7.  
  8. #[inline]
  9. pub fn get_postgres() -> &'static PgPool {
  10.    unsafe { POSTGRES.get_unchecked() }
  11. }
  12.  
  13. #[derive(FromRow, Serialize, Debug)]
  14. pub struct Page {
  15.    pub page_id: i64,
  16.    pub slug: String,
  17.    pub title: String,
  18.    pub content: String,
  19. }
  20.  
  21. #[handler]
  22. pub async fn get_page(req: &mut Request, res: &mut Response) {
  23.    let id = req.query::<i64>("id").unwrap();
  24.    let data = sqlx::query_as::<_, Page>("select * from pages where page_id = $1")
  25.        .bind(id)
  26.        .fetch_one(get_postgres())
  27.        .await
  28.        .unwrap();
  29.    res.render(serde_json::to_string(&data).unwrap());
  30. }
  31.  
  32. #[tokio::main]
  33. async fn main() {
  34.    tracing_subscriber::fmt().init();
  35.  
  36.    // postgresql connect info
  37.    let postgres_uri = "postgres://cms:gfhSyu65D3rewfth@localhost/cms";
  38.    let pool = PgPool::connect(postgres_uri).await.unwrap();
  39.    POSTGRES.set(pool).unwrap();
  40.  
  41.    // router
  42.    let router = Router::with_path("/<id>").get(get_page);
  43.  
  44.    tracing::info!("Listening on http://192.168.178.11:7878");
  45.    Server::new(TcpListener::bind("192.168.178.11:7878")).serve(router).await;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment