1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
use crate::{AddrStream, Error, Request, Response}; use async_std::net::{SocketAddr, TcpStream}; use async_std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard}; use http::header::{AsHeaderName, ToStrError}; use http::StatusCode; use http::{HeaderValue, Method, Uri, Version}; use std::any::TypeId; use std::collections::HashMap; use std::convert::AsRef; use std::fmt::Display; use std::ops::Deref; use std::str::FromStr; /// A structure to share request, response and other data between middlewares. /// /// Type of the first parameter in a middleware. /// /// ### Example /// /// ```rust /// use roa_core::App; /// use log::info; /// use async_std::fs::File; /// /// #[async_std::main] /// async fn main() -> Result<(), Box<dyn std::error::Error>> { /// let server = App::new(()) /// .gate_fn(|ctx, next| async move { /// info!("{} {}", ctx.method().await, ctx.uri().await); /// next().await /// }) /// .end(|ctx| async move { /// ctx.resp_mut().await.write(File::open("assets/welcome.html").await?); /// Ok(()) /// }) /// .listen("127.0.0.1:8000", |addr| { /// info!("Server is listening on {}", addr) /// })?; /// // server.await; /// Ok(()) /// } /// ``` pub struct Context<S> { request: Arc<RwLock<Request>>, response: Arc<RwLock<Response>>, state: Arc<RwLock<S>>, storage: Arc<RwLock<HashMap<TypeId, Bucket>>>, stream: AddrStream, } /// A wrapper of `HashMap<String, String>`, method `get` return a `Variable`. /// /// ### Example /// ```rust /// use roa_core::{Bucket, Variable}; /// let mut bucket = Bucket::new(); /// assert!(bucket.get("id").is_none()); /// assert!(bucket.insert("id", "1").is_none()); /// assert_eq!(1, bucket.get("id").unwrap().parse().unwrap()); /// assert_eq!(1, bucket.insert("id", "2").unwrap().parse().unwrap()); /// ``` #[derive(Debug, Clone)] pub struct Bucket(HashMap<String, String>); /// A wrapper of String. /// /// ### Example /// ```rust /// use roa_core::Variable; /// use http::StatusCode; /// assert_eq!(1, Variable::new("id", "1".to_string()).parse().unwrap()); /// let result = Variable::new("id", "x".to_string()).parse::<usize>(); /// assert!(result.is_err()); /// let status = result.unwrap_err(); /// assert_eq!(StatusCode::BAD_REQUEST, status.status_code); /// assert!(status.message.ends_with("type of variable `id` should be usize")); /// ``` #[derive(Debug, Clone)] pub struct Variable<'a> { name: &'a str, value: String, } impl Deref for Variable<'_> { type Target = str; #[inline] fn deref(&self) -> &Self::Target { &self.value } } impl AsRef<str> for Variable<'_> { #[inline] fn as_ref(&self) -> &str { &self } } impl<'a> Variable<'a> { /// Construct a variable from name and value. #[inline] pub fn new(name: &'a str, value: String) -> Self { Self { name, value } } /// A wrapper of `str::parse`. Converts `T::FromStr::Err` to `Status` automatically. /// /// ### Example /// ```rust /// use roa_core::Variable; /// use http::StatusCode; /// let result = Variable::new("id", "x".to_string()).parse::<usize>(); /// assert!(result.is_err()); /// let status = result.unwrap_err(); /// assert_eq!(StatusCode::BAD_REQUEST, status.status_code); /// assert!(status.message.ends_with("type of variable `id` should be usize")); /// ``` pub fn parse<T>(&self) -> Result<T, Error> where T: FromStr, T::Err: Display, { self.as_ref().parse().map_err(|err| { Error::new( StatusCode::BAD_REQUEST, format!( "{}\ntype of variable `{}` should be {}", err, self.name, std::any::type_name::<T>() ), true, ) }) } /// Into inner value. #[inline] pub fn into_value(self) -> String { self.value } } impl Bucket { /// Construct an empty Bucket. pub fn new() -> Self { Self(HashMap::new()) } /// Inserts a key-value pair into the bucket. /// /// If the bucket did not have this key present, [`None`] is returned. /// /// If the bucket did have this key present, the value is updated, and the old /// value is returned. /// /// ### Example /// ```rust /// use roa_core::{Bucket, Variable}; /// let mut bucket = Bucket::new(); /// assert!(bucket.insert("id", "1").is_none()); /// assert_eq!(1, bucket.insert("id", "2").unwrap().parse().unwrap()); /// ``` #[inline] pub fn insert<'a>(&mut self, name: &'a str, value: impl ToString) -> Option<Variable<'a>> { self.0 .insert(name.to_string(), value.to_string()) .map(|value| Variable::new(name, value)) } /// If the bucket did not have this key present, [`None`] is returned. /// /// If the bucket did have this key present, the key-value pair will be returned as a `Variable` /// /// ### Example /// ```rust /// use roa_core::{Bucket, Variable}; /// let mut bucket = Bucket::new(); /// assert!(bucket.get("id").is_none()); /// bucket.insert("id", "1"); /// assert_eq!(1, bucket.get("id").unwrap().parse().unwrap()); /// ``` #[inline] pub fn get<'a>(&self, name: &'a str) -> Option<Variable<'a>> { self.0.get(name).map(|value| Variable { name, value: value.to_string(), }) } } impl Default for Bucket { fn default() -> Self { Self::new() } } impl<S> Context<S> { /// Construct a context from a request, an app and a addr_stream. pub(crate) fn new(request: Request, state: S, stream: AddrStream) -> Self { Self { request: Arc::new(RwLock::new(request)), response: Arc::new(RwLock::new(Response::new())), state: Arc::new(RwLock::new(state)), storage: Arc::new(RwLock::new(HashMap::new())), stream, } } /// Get an immutable reference of request. /// /// ### Example /// ```rust /// use roa_core::App; /// use async_std::task::spawn; /// use http::{StatusCode, Method}; /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn std::error::Error>> { /// let (addr, server) = App::new(()) /// .end(|ctx| async move { /// assert_eq!(Method::GET, ctx.req().await.method); /// Ok(()) /// }) /// .run_local()?; /// spawn(server); /// let resp = reqwest::get(&format!("http://{}", addr)).await?; /// assert_eq!(StatusCode::OK, resp.status()); /// Ok(()) /// } /// ``` #[inline] pub async fn req(&self) -> RwLockReadGuard<'_, Request> { self.request.read().await } /// Get an immutable reference of response. /// /// ### Example /// ```rust /// use roa_core::App; /// use async_std::task::spawn; /// use http::StatusCode; /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn std::error::Error>> { /// let (addr, server) = App::new(()) /// .end(|ctx| async move { /// assert_eq!(StatusCode::OK, ctx.resp().await.status); /// Ok(()) /// }) /// .run_local()?; /// spawn(server); /// let resp = reqwest::get(&format!("http://{}", addr)).await?; /// assert_eq!(StatusCode::OK, resp.status()); /// Ok(()) /// } /// ``` #[inline] pub async fn resp(&self) -> RwLockReadGuard<'_, Response> { self.response.read().await } /// Get an immutable reference of state. /// /// ### Example /// ```rust /// use roa_core::{App, Model}; /// use log::info; /// use async_std::task::spawn; /// use http::StatusCode; /// /// struct AppModel { /// default_id: u64, /// } /// /// struct AppState { /// id: u64, /// } /// /// impl AppModel { /// fn new() -> Self { /// Self { /// default_id: 0, /// } /// } /// } /// /// impl Model for AppModel { /// type State = AppState; /// fn new_state(&self) -> Self::State { /// AppState { /// id: self.default_id, /// } /// } /// } /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn std::error::Error>> { /// let (addr, server) = App::new(AppModel::new()) /// .gate_fn(|ctx, next| async move { /// ctx.state_mut().await.id = 1; /// next().await /// }) /// .end(|ctx| async move { /// let id = ctx.state().await.id; /// assert_eq!(1, id); /// Ok(()) /// }) /// .run_local()?; /// spawn(server); /// let resp = reqwest::get(&format!("http://{}", addr)).await?; /// assert_eq!(StatusCode::OK, resp.status()); /// Ok(()) /// } /// ``` #[inline] pub async fn state(&self) -> RwLockReadGuard<'_, S> { self.state.read().await } /// Get an immutable reference of storage. #[inline] pub(crate) async fn storage(&self) -> RwLockReadGuard<'_, HashMap<TypeId, Bucket>> { self.storage.read().await } /// Get a mutable reference of request. /// /// ### Example /// ```rust /// use roa_core::App; /// use async_std::task::spawn; /// use http::{StatusCode, Method}; /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn std::error::Error>> { /// let (addr, server) = App::new(()) /// .gate_fn(|ctx, next| async move { /// ctx.req_mut().await.method = Method::POST; /// next().await /// }) /// .end(|ctx| async move { /// assert_eq!(Method::POST, ctx.req().await.method); /// Ok(()) /// }) /// .run_local()?; /// spawn(server); /// let resp = reqwest::get(&format!("http://{}", addr)).await?; /// assert_eq!(StatusCode::OK, resp.status()); /// Ok(()) /// } /// ``` #[inline] pub async fn req_mut(&self) -> RwLockWriteGuard<'_, Request> { self.request.write().await } /// Get a mutable reference of response. /// /// ### Example /// ```rust /// use roa_core::App; /// use async_std::task::spawn; /// use http::StatusCode; /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn std::error::Error>> { /// let (addr, server) = App::new(()) /// .end(|ctx| async move { /// ctx.resp_mut().await.write_buf(b"Hello, World!".as_ref()); /// Ok(()) /// }) /// .run_local()?; /// spawn(server); /// let resp = reqwest::get(&format!("http://{}", addr)).await?; /// assert_eq!(StatusCode::OK, resp.status()); /// assert_eq!("Hello, World!", resp.text().await?); /// Ok(()) /// } /// ``` #[inline] pub async fn resp_mut(&self) -> RwLockWriteGuard<'_, Response> { self.response.write().await } /// Get a mutable reference of state. /// /// ### Example /// ```rust /// use roa_core::{App, Model}; /// use log::info; /// use async_std::task::spawn; /// use http::StatusCode; /// /// struct AppModel { /// default_id: u64, /// } /// /// struct AppState { /// id: u64, /// } /// /// impl AppModel { /// fn new() -> Self { /// Self { /// default_id: 0, /// } /// } /// } /// /// impl Model for AppModel { /// type State = AppState; /// fn new_state(&self) -> Self::State { /// AppState { /// id: self.default_id, /// } /// } /// } /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn std::error::Error>> { /// let (addr, server) = App::new(AppModel::new()) /// .gate_fn(|ctx, next| async move { /// ctx.state_mut().await.id = 1; /// next().await /// }) /// .end(|ctx| async move { /// let id = ctx.state().await.id; /// assert_eq!(1, id); /// Ok(()) /// }) /// .run_local()?; /// spawn(server); /// let resp = reqwest::get(&format!("http://{}", addr)).await?; /// assert_eq!(StatusCode::OK, resp.status()); /// Ok(()) /// } /// ``` #[inline] pub async fn state_mut(&self) -> RwLockWriteGuard<'_, S> { self.state.write().await } /// Get a mutable reference of storage. #[inline] pub(crate) async fn storage_mut(&self) -> RwLockWriteGuard<'_, HashMap<TypeId, Bucket>> { self.storage.write().await } /// Clone URI. /// /// ### Example /// ```rust /// use roa_core::App; /// use async_std::task::spawn; /// use http::{StatusCode, Method}; /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn std::error::Error>> { /// let (addr, server) = App::new(()) /// .end(|ctx| async move { /// assert_eq!("/path", ctx.uri().await.to_string()); /// Ok(()) /// }) /// .run_local()?; /// spawn(server); /// let resp = reqwest::get(&format!("http://{}/path", addr)).await?; /// assert_eq!(StatusCode::OK, resp.status()); /// Ok(()) /// } /// ``` pub async fn uri(&self) -> Uri { self.req().await.uri.clone() } /// Clone request::method. /// /// ### Example /// ```rust /// use roa_core::App; /// use async_std::task::spawn; /// use http::{StatusCode, Method}; /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn std::error::Error>> { /// let (addr, server) = App::new(()) /// .end(|ctx| async move { /// assert_eq!(Method::GET, ctx.method().await); /// Ok(()) /// }) /// .run_local()?; /// spawn(server); /// let resp = reqwest::get(&format!("http://{}/path", addr)).await?; /// assert_eq!(StatusCode::OK, resp.status()); /// Ok(()) /// } /// ``` pub async fn method(&self) -> Method { self.req().await.method.clone() } /// Search for a header value and try to get its string copy. /// /// ### Example /// ```rust /// use roa_core::App; /// use async_std::task::spawn; /// use http::{StatusCode, Method, header}; /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn std::error::Error>> { /// let (addr, server) = App::new(()) /// .end(|ctx| async move { /// assert_eq!( /// "text/plain", /// ctx.header(&header::CONTENT_TYPE).await.unwrap().unwrap() /// ); /// Ok(()) /// }) /// .run_local()?; /// spawn(server); /// let resp = reqwest::Client::new() /// .get(&format!("http://{}", addr)) /// .header(&header::CONTENT_TYPE, "text/plain") /// .send() /// .await?; /// assert_eq!(StatusCode::OK, resp.status()); /// Ok(()) /// } /// ``` pub async fn header(&self, name: impl AsHeaderName) -> Option<Result<String, ToStrError>> { self.req() .await .headers .get(name) .map(|value| value.to_str().map(|str| str.to_string())) } /// Search for a header value and clone it. /// /// ### Example /// ```rust /// use roa_core::App; /// use async_std::task::spawn; /// use http::{StatusCode, Method, header}; /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn std::error::Error>> { /// let (addr, server) = App::new(()) /// .end(|ctx| async move { /// assert_eq!( /// "text/plain", /// ctx.header_value(&header::CONTENT_TYPE).await.unwrap().to_str().unwrap() /// ); /// Ok(()) /// }) /// .run_local()?; /// spawn(server); /// let resp = reqwest::Client::new() /// .get(&format!("http://{}", addr)) /// .header(&header::CONTENT_TYPE, "text/plain") /// .send() /// .await?; /// assert_eq!(StatusCode::OK, resp.status()); /// Ok(()) /// } /// ``` pub async fn header_value(&self, name: impl AsHeaderName) -> Option<HeaderValue> { self.req().await.headers.get(name).cloned() } /// Clone response::status. /// /// ### Example /// ```rust /// use roa_core::App; /// use async_std::task::spawn; /// use http::{StatusCode, Method}; /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn std::error::Error>> { /// let (addr, server) = App::new(()) /// .end(|ctx| async move { /// assert_eq!(StatusCode::OK, ctx.status().await); /// Ok(()) /// }) /// .run_local()?; /// spawn(server); /// let resp = reqwest::get(&format!("http://{}/path", addr)).await?; /// assert_eq!(StatusCode::OK, resp.status()); /// Ok(()) /// } /// ``` pub async fn status(&self) -> StatusCode { self.resp().await.status } /// Clone request::version. /// /// ### Example /// ```rust /// use roa_core::App; /// use async_std::task::spawn; /// use http::{StatusCode, Version}; /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn std::error::Error>> { /// let (addr, server) = App::new(()) /// .end(|ctx| async move { /// assert_eq!(Version::HTTP_11, ctx.version().await); /// Ok(()) /// }) /// .run_local()?; /// spawn(server); /// let resp = reqwest::get(&format!("http://{}/path", addr)).await?; /// assert_eq!(StatusCode::OK, resp.status()); /// Ok(()) /// } /// ``` pub async fn version(&self) -> Version { self.req().await.version } /// Store key-value pair. Each type has its namespace. /// /// ### Example /// ```rust /// use roa_core::App; /// use async_std::task::spawn; /// use http::{StatusCode, Method}; /// /// struct Symbol; /// struct AnotherSymbol; /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn std::error::Error>> { /// let (addr, server) = App::new(()) /// .gate_fn(|ctx, next| async move { /// ctx.store::<Symbol>("id", "1".to_owned()).await; /// next().await /// }) /// .end(|ctx| async move { /// assert_eq!(1, ctx.load::<Symbol>("id").await.unwrap().parse::<i32>()?); /// assert!(ctx.load::<AnotherSymbol>("id").await.is_none()); /// Ok(()) /// }) /// .run_local()?; /// spawn(server); /// let resp = reqwest::get(&format!("http://{}/path", addr)).await?; /// assert_eq!(StatusCode::OK, resp.status()); /// Ok(()) /// } /// ``` #[allow(clippy::needless_lifetimes)] pub async fn store<'a, T: 'static>( &self, name: &'a str, value: String, ) -> Option<Variable<'a>> { let mut storage = self.storage_mut().await; let id = TypeId::of::<T>(); match storage.get_mut(&id) { Some(bucket) => bucket.insert(name, value), None => { let mut bucket = Bucket::default(); bucket.insert(name, value); storage.insert(id, bucket); None } } } /// Search for value by key. /// /// ### Example /// /// ```rust /// use roa_core::App; /// use async_std::task::spawn; /// use http::{StatusCode, Method}; /// /// struct Symbol; /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn std::error::Error>> { /// let (addr, server) = App::new(()) /// .gate_fn(|ctx, next| async move { /// ctx.store::<Symbol>("id", "1".to_owned()).await; /// next().await /// }) /// .end(|ctx| async move { /// assert_eq!(1, ctx.load::<Symbol>("id").await.unwrap().parse::<i32>()?); /// Ok(()) /// }) /// .run_local()?; /// spawn(server); /// let resp = reqwest::get(&format!("http://{}/path", addr)).await?; /// assert_eq!(StatusCode::OK, resp.status()); /// Ok(()) /// } /// ``` /// /// ### Parse fails /// /// The loaded value can be parsed as str, and return a 400 BAD REQUEST Error if fails. /// /// ```rust /// use roa_core::App; /// use async_std::task::spawn; /// use http::{StatusCode, Method}; /// /// struct Symbol; /// /// #[tokio::main] /// async fn main() -> Result<(), Box<dyn std::error::Error>> { /// let (addr, server) = App::new(()) /// .gate_fn(|ctx, next| async move { /// ctx.store::<Symbol>("id", "x".to_owned()).await; /// next().await /// }) /// .end(|ctx| async move { /// assert_eq!(1, ctx.load::<Symbol>("id").await.unwrap().parse::<i32>()?); /// Ok(()) /// }) /// .run_local()?; /// spawn(server); /// let resp = reqwest::get(&format!("http://{}/path", addr)).await?; /// assert_eq!(StatusCode::BAD_REQUEST, resp.status()); /// Ok(()) /// } /// ``` #[allow(clippy::needless_lifetimes)] pub async fn load<'a, T: 'static>(&self, name: &'a str) -> Option<Variable<'a>> { let storage = self.storage().await; let id = TypeId::of::<T>(); storage.get(&id).and_then(|bucket| bucket.get(name)) } /// Get remote socket addr. pub fn remote_addr(&self) -> SocketAddr { self.stream.remote_addr() } /// Get reference of raw async_std::net::TcpStream. /// This method is dangerous, it's reserved for special scene like websocket. pub fn raw_stream(&self) -> &TcpStream { self.stream.stream() } } impl<S> Clone for Context<S> { fn clone(&self) -> Self { Self { request: self.request.clone(), response: self.response.clone(), state: self.state.clone(), storage: self.storage.clone(), stream: self.stream.clone(), } } } #[cfg(test)] mod tests { use crate::{App, Context, Model}; use async_std::task::spawn; use http::{StatusCode, Version}; #[tokio::test] async fn status_and_version() -> Result<(), Box<dyn std::error::Error>> { let (addr, server) = App::new(()) .end(|ctx| async move { assert_eq!(Version::HTTP_11, ctx.version().await); assert_eq!(StatusCode::OK, ctx.status().await); Ok(()) }) .run_local()?; spawn(server); reqwest::get(&format!("http://{}", addr)).await?; Ok(()) } struct AppModel; struct AppState { data: usize, } impl Model for AppModel { type State = AppState; fn new_state(&self) -> Self::State { AppState { data: 0 } } } #[tokio::test] async fn state_mut() -> Result<(), Box<dyn std::error::Error>> { let (addr, server) = App::new(AppModel {}) .gate_fn(|ctx, next| async move { ctx.state_mut().await.data = 1; next().await }) .end(|ctx: Context<AppState>| async move { assert_eq!(1, ctx.state().await.data); Ok(()) }) .run_local()?; spawn(server); reqwest::get(&format!("http://{}", addr)).await?; Ok(()) } }