-
Hi, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
With Routerify you can use any db library that supports Cargo.toml[dependencies]
tokio = { version = "1", features = ["full"] }
hyper = { version = "0.14", features = ["full"] }
routerify = "2"
sqlx = { version = "0.5", features = [ "runtime-tokio-rustls", "postgres" ] }
main.rsuse hyper::{Body, Request, Response, Server};
use routerify::prelude::*;
use routerify::{Router, RouterService};
use sqlx::postgres;
use std::{convert::Infallible, net::SocketAddr};
struct Service {
db_pool: postgres::PgPool,
}
async fn home(req: Request<Body>) -> Result<Response<Body>, Infallible> {
// Access the Serice instance.
let service = req.data::<Service>().unwrap();
let n_conn = service.db_pool.size();
Ok(Response::new(format!("{} db connections", n_conn).into()))
}
#[tokio::main]
async fn main() {
// Create new db pool.
let pool = postgres::PgPoolOptions::new()
// Make sure to use correct connection string.
.connect("postgres://postgres:postgres@localhost/testdb")
.await
.expect("unable to create postgresql pool");
// Create a Service with the db pool.
let service = Service { db_pool: pool };
// Pass the Service as shared data to the router; it can be
// accessed by every handler (inclding error) and middleware.
let router = Router::builder()
.data(service)
.get("/", home)
.build()
.unwrap();
let service = RouterService::new(router).unwrap();
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let server = Server::bind(&addr).serve(service);
println!("App is running on: {}", addr);
if let Err(err) = server.await {
eprintln!("Server error: {}", err);
}
} You don't have to use the |
Beta Was this translation helpful? Give feedback.
With Routerify you can use any db library that supports
tokio
. Initialize the pool and then pass it as shared data to a router instance.Here's a simple yet fully functional example using sqlx and Postgres.
Cargo.toml
main.rs