Skip to content
Myr

main.rs

This file

Path

examples/tokio-postgres/src/main.rs

105 lines · 3.0 KiB · Rust

Last changed by

Fix return types of serve futures (#3601)Jonas Plattebefore adoptionf3a95d7

History of this file

Take it

1//! Run with2//!3//! ```not_rust4//! cargo run -p example-tokio-postgres5//! ```67use axum::{8    extract::{FromRef, FromRequestParts, State},9    http::{request::Parts, StatusCode},10    routing::get,11    Router,12};13use bb8::{Pool, PooledConnection};14use bb8_postgres::PostgresConnectionManager;15use tokio_postgres::NoTls;16use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};1718#[tokio::main]19async fn main() {20    tracing_subscriber::registry()21        .with(22            tracing_subscriber::EnvFilter::try_from_default_env()23                .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),24        )25        .with(tracing_subscriber::fmt::layer())26        .init();2728    // set up connection pool29    let manager =30        PostgresConnectionManager::new_from_stringlike("host=localhost user=postgres", NoTls)31            .unwrap();32    let pool = Pool::builder().build(manager).await.unwrap();3334    // build our application with some routes35    let app = Router::new()36        .route(37            "/",38            get(using_connection_pool_extractor).post(using_connection_extractor),39        )40        .with_state(pool);4142    // run it43    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")44        .await45        .unwrap();46    tracing::debug!("listening on {}", listener.local_addr().unwrap());47    axum::serve(listener, app).await;48}4950type ConnectionPool = Pool<PostgresConnectionManager<NoTls>>;5152async fn using_connection_pool_extractor(53    State(pool): State<ConnectionPool>,54) -> Result<String, (StatusCode, String)> {55    let conn = pool.get().await.map_err(internal_error)?;5657    let row = conn58        .query_one("select 1 + 1", &[])59        .await60        .map_err(internal_error)?;61    let two: i32 = row.try_get(0).map_err(internal_error)?;6263    Ok(two.to_string())64}6566// we can also write a custom extractor that grabs a connection from the pool67// which setup is appropriate depends on your application68struct DatabaseConnection(PooledConnection<'static, PostgresConnectionManager<NoTls>>);6970impl<S> FromRequestParts<S> for DatabaseConnection71where72    ConnectionPool: FromRef<S>,73    S: Send + Sync,74{75    type Rejection = (StatusCode, String);7677    async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {78        let pool = ConnectionPool::from_ref(state);7980        let conn = pool.get_owned().await.map_err(internal_error)?;8182        Ok(Self(conn))83    }84}8586async fn using_connection_extractor(87    DatabaseConnection(conn): DatabaseConnection,88) -> Result<String, (StatusCode, String)> {89    let row = conn90        .query_one("select 1 + 1", &[])91        .await92        .map_err(internal_error)?;93    let two: i32 = row.try_get(0).map_err(internal_error)?;9495    Ok(two.to_string())96}9798/// Utility function for mapping any error into a `500 Internal Server Error`99/// response.100fn internal_error<E>(err: E) -> (StatusCode, String)101where102    E: std::error::Error,103{104    (StatusCode::INTERNAL_SERVER_ERROR, err.to_string())105}