1
+ use std:: io:: Error as IoError ;
2
+ use std:: path:: Path ;
1
3
use std:: sync:: Arc ;
2
4
3
5
use async_std:: { fs:: OpenOptions , io} ;
4
6
use tempfile:: TempDir ;
5
7
use tide:: prelude:: * ;
6
8
use tide:: { Body , Request , Response , StatusCode } ;
7
9
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
+
8
27
#[ async_std:: main]
9
- async fn main ( ) -> Result < ( ) , std :: io :: Error > {
28
+ async fn main ( ) -> Result < ( ) , IoError > {
10
29
tide:: log:: start ( ) ;
11
- let mut app = tide:: with_state ( Arc :: new ( tempfile :: tempdir ( ) ? ) ) ;
30
+ let mut app = tide:: with_state ( TempDirState :: try_new ( ) ? ) ;
12
31
13
32
// To test this example:
14
33
// $ cargo run --example upload
15
34
// $ curl -T ./README.md locahost:8080 # this writes the file to a temp directory
16
35
// $ curl localhost:8080/README.md # this reads the file from the same temp directory
17
36
18
37
app. at ( ":file" )
19
- . put ( |req : Request < Arc < TempDir > > | async move {
38
+ . put ( |req : Request < TempDirState > | async move {
20
39
let path: String = req. param ( "file" ) ?;
21
40
let fs_path = req. state ( ) . path ( ) . join ( path) ;
22
41
@@ -35,7 +54,7 @@ async fn main() -> Result<(), std::io::Error> {
35
54
36
55
Ok ( json ! ( { "bytes" : bytes_written } ) )
37
56
} )
38
- . get ( |req : Request < Arc < TempDir > > | async move {
57
+ . get ( |req : Request < TempDirState > | async move {
39
58
let path: String = req. param ( "file" ) ?;
40
59
let fs_path = req. state ( ) . path ( ) . join ( path) ;
41
60
0 commit comments