Skip to content

Commit 30c2443

Browse files
committed
Examples: improve state handling in upload example
Addresses #644 (review)
1 parent 50bc628 commit 30c2443

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

examples/upload.rs

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,41 @@
1+
use std::io::Error as IoError;
2+
use std::path::Path;
13
use std::sync::Arc;
24

35
use async_std::{fs::OpenOptions, io};
46
use tempfile::TempDir;
57
use tide::prelude::*;
68
use tide::{Body, Request, Response, StatusCode};
79

10+
#[derive(Clone)]
11+
struct TempDirState {
12+
tempdir: Arc<TempDir>,
13+
}
14+
15+
impl TempDirState {
16+
fn try_new() -> Result<Self, IoError> {
17+
Ok(Self {
18+
tempdir: Arc::new(tempfile::tempdir()?),
19+
})
20+
}
21+
22+
fn path(&self) -> &Path {
23+
self.tempdir.path()
24+
}
25+
}
26+
827
#[async_std::main]
9-
async fn main() -> Result<(), std::io::Error> {
28+
async fn main() -> Result<(), IoError> {
1029
tide::log::start();
11-
let mut app = tide::with_state(Arc::new(tempfile::tempdir()?));
30+
let mut app = tide::with_state(TempDirState::try_new()?);
1231

1332
// To test this example:
1433
// $ cargo run --example upload
1534
// $ curl -T ./README.md locahost:8080 # this writes the file to a temp directory
1635
// $ curl localhost:8080/README.md # this reads the file from the same temp directory
1736

1837
app.at(":file")
19-
.put(|req: Request<Arc<TempDir>>| async move {
38+
.put(|req: Request<TempDirState>| async move {
2039
let path: String = req.param("file")?;
2140
let fs_path = req.state().path().join(path);
2241

@@ -35,7 +54,7 @@ async fn main() -> Result<(), std::io::Error> {
3554

3655
Ok(json!({ "bytes": bytes_written }))
3756
})
38-
.get(|req: Request<Arc<TempDir>>| async move {
57+
.get(|req: Request<TempDirState>| async move {
3958
let path: String = req.param("file")?;
4059
let fs_path = req.state().path().join(path);
4160

0 commit comments

Comments
 (0)