-
-
Save Skepfyr/2d64b66a11f93107a76782347b76b32d to your computer and use it in GitHub Desktop.
Simple hyper server with limited number of concurret requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "tower-test" | |
version = "0.1.0" | |
edition = "2021" | |
[dependencies] | |
color-eyre = "0.6.1" | |
hyper = { version = "0.14.18", features = ["full"] } | |
tokio = { version = "1.17.0", features = ["full"] } | |
tower = { version = "0.4.12", features = ["full"] } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::{convert::Infallible, net::Ipv4Addr, sync::Arc}; | |
use color_eyre::eyre; | |
use hyper::{Body, Response}; | |
use tokio::sync::Semaphore; | |
use tower::{limit::ConcurrencyLimit, make::Shared, ServiceBuilder}; | |
#[tokio::main] | |
async fn main() -> eyre::Result<()> { | |
let semaphore = Arc::new(Semaphore::const_new(2)); | |
let service = ServiceBuilder::new() | |
.layer_fn(|inner| ConcurrencyLimit::with_semaphore(inner, semaphore.clone())) | |
.service_fn( | |
|_req| async move { Ok::<_, Infallible>(Response::new(Body::from("Hello World"))) }, | |
); | |
let make_service = Shared::new(service); | |
let server = | |
hyper::Server::bind(&(Ipv4Addr::LOCALHOST, 8080).try_into().unwrap()).serve(make_service); | |
Ok(server.await?) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment