1
+ use url:: Url ;
1
2
pub use wasi:: http:: types:: {
2
3
Fields , IncomingRequest , OutgoingBody , OutgoingResponse , ResponseOutparam ,
3
4
} ;
@@ -6,18 +7,59 @@ struct Component;
6
7
wasi:: http:: proxy:: export!( Component ) ;
7
8
8
9
impl 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" ) ;
10
+ fn handle ( req : IncomingRequest , outparam : ResponseOutparam ) {
11
+ let url = req. path_with_query ( ) . unwrap ( ) ;
12
+ let url = Url :: parse ( & url) . expect ( "could not parse the URL" ) ;
13
+ http_home ( req, outparam) ;
14
+ // dbg!(&url);
15
+ // match url.path() {
16
+ // "/wait" => http_wait(req, outparam),
17
+ // // "/echo" => {} // TODO
18
+ // // "/host" => {} // TODO
19
+ // "/" | _ => http_home(req, outparam),
20
+ // }
21
+ }
22
+ }
13
23
14
- ResponseOutparam :: set ( outparam, Ok ( resp) ) ;
24
+ fn http_home ( _req : IncomingRequest , outparam : ResponseOutparam ) {
25
+ let headers = Fields :: new ( ) ;
26
+ let res = OutgoingResponse :: new ( headers) ;
27
+ let body = res. body ( ) . expect ( "outgoing response" ) ;
15
28
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" ) ;
29
+ ResponseOutparam :: set ( outparam, Ok ( res) ) ;
19
30
20
- drop ( out) ;
21
- OutgoingBody :: finish ( body, None ) . unwrap ( ) ;
22
- }
31
+ let out = body. write ( ) . expect ( "outgoing stream" ) ;
32
+ out. blocking_write_and_flush ( b"Hello, wasi:http/proxy world!\n " )
33
+ . expect ( "writing response" ) ;
34
+
35
+ drop ( out) ;
36
+ OutgoingBody :: finish ( body, None ) . unwrap ( ) ;
37
+ }
38
+
39
+ fn http_wait ( _req : IncomingRequest , outparam : ResponseOutparam ) {
40
+ // Get the time now
41
+ let now = wasi:: clocks:: monotonic_clock:: now ( ) ;
42
+
43
+ // Sleep for 1 second
44
+ let nanos = 1_000_000_000 ;
45
+ let pollable = wasi:: clocks:: monotonic_clock:: subscribe_duration ( nanos) ;
46
+ pollable. block ( ) ;
47
+
48
+ // Compute how long we slept for.
49
+ let elapsed = wasi:: clocks:: monotonic_clock:: now ( ) - now;
50
+ let elapsed = elapsed / 1_000_000 ; // change to millis
51
+
52
+ let headers = Fields :: new ( ) ;
53
+ let res = OutgoingResponse :: new ( headers) ;
54
+ let body = res. body ( ) . expect ( "outgoing response" ) ;
55
+
56
+ ResponseOutparam :: set ( outparam, Ok ( res) ) ;
57
+
58
+ let out = body. write ( ) . expect ( "outgoing stream" ) ;
59
+ let msg = format ! ( "slept for {elapsed} millis" ) ;
60
+ out. blocking_write_and_flush ( msg. as_bytes ( ) )
61
+ . expect ( "writing response" ) ;
62
+
63
+ drop ( out) ;
64
+ OutgoingBody :: finish ( body, None ) . unwrap ( ) ;
23
65
}
0 commit comments