File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ use async_std:: { fs:: OpenOptions , io} ;
2+ use tempfile:: TempDir ;
3+ use tide:: prelude:: * ;
4+ use tide:: { Body , Request , Response , StatusCode } ;
5+
6+ #[ async_std:: main]
7+ async fn main ( ) -> Result < ( ) , std:: io:: Error > {
8+ tide:: log:: start ( ) ;
9+ let mut app = tide:: with_state ( tempfile:: tempdir ( ) ?) ;
10+
11+ // To test this example:
12+ // $ cargo run --example upload
13+ // $ curl -T ./README.md locahost:8080 # this writes the file to a temp directory
14+ // $ curl localhost:8080/README.md # this reads the file from the same temp directory
15+
16+ app. at ( ":file" )
17+ . put ( |req : Request < TempDir > | async move {
18+ let path: String = req. param ( "file" ) ?;
19+ let fs_path = req. state ( ) . path ( ) . join ( path) ;
20+
21+ let file = OpenOptions :: new ( )
22+ . create ( true )
23+ . write ( true )
24+ . open ( & fs_path)
25+ . await ?;
26+
27+ let bytes_written = io:: copy ( req, file) . await ?;
28+
29+ tide:: log:: info!( "file written" , {
30+ bytes: bytes_written,
31+ path: fs_path. canonicalize( ) ?. to_str( )
32+ } ) ;
33+
34+ Ok ( json ! ( { "bytes" : bytes_written } ) )
35+ } )
36+ . get ( |req : Request < TempDir > | async move {
37+ let path: String = req. param ( "file" ) ?;
38+ let fs_path = req. state ( ) . path ( ) . join ( path) ;
39+
40+ if let Ok ( body) = Body :: from_file ( fs_path) . await {
41+ Ok ( body. into ( ) )
42+ } else {
43+ Ok ( Response :: new ( StatusCode :: NotFound ) )
44+ }
45+ } ) ;
46+
47+ app. listen ( "127.0.0.1:8080" ) . await ?;
48+ Ok ( ( ) )
49+ }
You can’t perform that action at this time.
0 commit comments