@@ -6,18 +6,55 @@ struct Component;
66wasi:: http:: proxy:: export!( Component ) ;
77
88impl wasi:: exports:: http:: incoming_handler:: Guest for Component {
9- fn handle ( _request : IncomingRequest , outparam : ResponseOutparam ) {
10- let hdrs = Fields :: new ( ) ;
11- let resp = OutgoingResponse :: new ( hdrs) ;
12- let body = resp. body ( ) . expect ( "outgoing response" ) ;
9+ fn handle ( req : IncomingRequest , outparam : ResponseOutparam ) {
10+ match req. path_with_query ( ) . unwrap ( ) . as_str ( ) {
11+ "/wait" => http_wait ( req, outparam) ,
12+ // "/echo" => {} // TODO
13+ // "/host" => {} // TODO
14+ "/" | _ => http_home ( req, outparam) ,
15+ }
16+ }
17+ }
1318
14- ResponseOutparam :: set ( outparam, Ok ( resp) ) ;
19+ fn http_home ( _req : IncomingRequest , outparam : ResponseOutparam ) {
20+ let headers = Fields :: new ( ) ;
21+ let res = OutgoingResponse :: new ( headers) ;
22+ let body = res. body ( ) . expect ( "outgoing response" ) ;
1523
16- let out = body. write ( ) . expect ( "outgoing stream" ) ;
17- out. blocking_write_and_flush ( b"Hello, wasi:http/proxy world!\n " )
18- . expect ( "writing response" ) ;
24+ ResponseOutparam :: set ( outparam, Ok ( res) ) ;
1925
20- drop ( out) ;
21- OutgoingBody :: finish ( body, None ) . unwrap ( ) ;
22- }
26+ let out = body. write ( ) . expect ( "outgoing stream" ) ;
27+ out. blocking_write_and_flush ( b"Hello, wasi:http/proxy world!\n " )
28+ . expect ( "writing response" ) ;
29+
30+ drop ( out) ;
31+ OutgoingBody :: finish ( body, None ) . unwrap ( ) ;
32+ }
33+
34+ fn http_wait ( _req : IncomingRequest , outparam : ResponseOutparam ) {
35+ // Get the time now
36+ let now = wasi:: clocks:: monotonic_clock:: now ( ) ;
37+
38+ // Sleep for 1 second
39+ let nanos = 1_000_000_000 ;
40+ let pollable = wasi:: clocks:: monotonic_clock:: subscribe_duration ( nanos) ;
41+ pollable. block ( ) ;
42+
43+ // Compute how long we slept for.
44+ let elapsed = wasi:: clocks:: monotonic_clock:: now ( ) - now;
45+ let elapsed = elapsed / 1_000_000 ; // change to millis
46+
47+ let headers = Fields :: new ( ) ;
48+ let res = OutgoingResponse :: new ( headers) ;
49+ let body = res. body ( ) . expect ( "outgoing response" ) ;
50+
51+ ResponseOutparam :: set ( outparam, Ok ( res) ) ;
52+
53+ let out = body. write ( ) . expect ( "outgoing stream" ) ;
54+ let msg = format ! ( "slept for {elapsed} millis\n " ) ;
55+ out. blocking_write_and_flush ( msg. as_bytes ( ) )
56+ . expect ( "writing response" ) ;
57+
58+ drop ( out) ;
59+ OutgoingBody :: finish ( body, None ) . unwrap ( ) ;
2360}
0 commit comments