Skip to content

Commit 8d1dd06

Browse files
authored
Fix HTTP body example. (#32)
Signed-off-by: Piotr Sikora <piotrsikora@google.com>
1 parent f352a8d commit 8d1dd06

File tree

1 file changed

+6
-22
lines changed

1 file changed

+6
-22
lines changed

examples/http_body.rs

Lines changed: 6 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -18,19 +18,10 @@ use proxy_wasm::types::*;
1818
#[no_mangle]
1919
pub fn _start() {
2020
proxy_wasm::set_log_level(LogLevel::Trace);
21-
proxy_wasm::set_http_context(|_, _| -> Box<dyn HttpContext> { Box::new(HttpBody::new()) });
21+
proxy_wasm::set_http_context(|_, _| -> Box<dyn HttpContext> { Box::new(HttpBody) });
2222
}
2323

24-
#[derive(Default)]
25-
struct HttpBody {
26-
total_body_size: usize,
27-
}
28-
29-
impl HttpBody {
30-
fn new() -> HttpBody {
31-
Default::default()
32-
}
33-
}
24+
struct HttpBody;
3425

3526
impl Context for HttpBody {}
3627

@@ -41,13 +32,10 @@ impl HttpContext for HttpBody {
4132
// We must do this here, because once we exit this function we
4233
// can no longer modify the response headers.
4334
self.set_http_response_header("content-length", None);
44-
// Don't continue to the next callout in the chain because we might
45-
// modify the body.
46-
Action::Pause
35+
Action::Continue
4736
}
4837

4938
fn on_http_response_body(&mut self, body_size: usize, end_of_stream: bool) -> Action {
50-
self.total_body_size += body_size;
5139
if !end_of_stream {
5240
// Wait -- we'll be called again when the complete body is buffered
5341
// at the host side.
@@ -56,15 +44,11 @@ impl HttpContext for HttpBody {
5644

5745
// Replace the message body if it contains the text "secret".
5846
// Since we returned "Pause" previuously, this will return the whole body.
59-
// However, we have to calculate the size ourselves.
60-
if let Some(body_bytes) = self.get_http_response_body(0, self.total_body_size) {
47+
if let Some(body_bytes) = self.get_http_response_body(0, body_size) {
6148
let body_str = String::from_utf8(body_bytes).unwrap();
6249
if body_str.find("secret").is_some() {
63-
let new_body = format!(
64-
"Original message body ({} bytes) redacted.",
65-
self.total_body_size
66-
);
67-
self.set_http_response_body(0, self.total_body_size, &new_body.into_bytes());
50+
let new_body = format!("Original message body ({} bytes) redacted.", body_size);
51+
self.set_http_response_body(0, body_size, &new_body.into_bytes());
6852
}
6953
}
7054
Action::Continue

0 commit comments

Comments
 (0)