Skip to content

Commit

Permalink
Examples: improve state handling in upload example
Browse files Browse the repository at this point in the history
Addresses
#644 (review)
  • Loading branch information
Fishrock123 committed Jul 17, 2020
1 parent 50bc628 commit 30c2443
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions examples/upload.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,41 @@
use std::io::Error as IoError;
use std::path::Path;
use std::sync::Arc;

use async_std::{fs::OpenOptions, io};
use tempfile::TempDir;
use tide::prelude::*;
use tide::{Body, Request, Response, StatusCode};

#[derive(Clone)]
struct TempDirState {
tempdir: Arc<TempDir>,
}

impl TempDirState {
fn try_new() -> Result<Self, IoError> {
Ok(Self {
tempdir: Arc::new(tempfile::tempdir()?),
})
}

fn path(&self) -> &Path {
self.tempdir.path()
}
}

#[async_std::main]
async fn main() -> Result<(), std::io::Error> {
async fn main() -> Result<(), IoError> {
tide::log::start();
let mut app = tide::with_state(Arc::new(tempfile::tempdir()?));
let mut app = tide::with_state(TempDirState::try_new()?);

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

app.at(":file")
.put(|req: Request<Arc<TempDir>>| async move {
.put(|req: Request<TempDirState>| async move {
let path: String = req.param("file")?;
let fs_path = req.state().path().join(path);

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

Ok(json!({ "bytes": bytes_written }))
})
.get(|req: Request<Arc<TempDir>>| async move {
.get(|req: Request<TempDirState>| async move {
let path: String = req.param("file")?;
let fs_path = req.state().path().join(path);

Expand Down

0 comments on commit 30c2443

Please sign in to comment.