worker-rs: http hello world

use worker::*;

#[event(fetch)]
async fn fetch(
_req: HttpRequest,
_env: Env,
_ctx: Context,
) -> Result<HttpResponse> {
console_error_panic_hook::set_once();
Ok(http::Response::builder()
.status(http::StatusCode::OK)
.body(Body::empty())?)
}
use worker::*;

#[event(fetch)]
async fn fetch(
_req: HttpRequest,
_env: Env,
_ctx: Context,
) -> Result<HttpResponse> {
console_error_panic_hook::set_once();
Ok(http::Response::builder()
.status(http::StatusCode::OK)
.body(Body::empty())?)
}
How can I put a simple string into the body? Tried many ways but didn't work. The body seems to be only accepting a stream. (http feature flag enabled for worker-rs)
5 Replies
Chihwei
ChihweiOP6mo ago
Thanks! Most of those examples are not with http feature flag turned on, which they are using older Response defined in worker-rs, rather than more widely used rust http crate. I later found I could change the wrapped type of Result to assign it a string, like Result<String>. I am a beginner of Rust, so let me know if I was wrong on anything.
Jeroen
Jeroen3mo ago
I am pulling my hear out trying to figure out the same thing. Did you ever figure it out, @Chihwei?
Chihwei
ChihweiOP3mo ago
@Jeroen
fn router() -> Router {
Router::new()
.route("/", get(root))
.route("/zhiwei", get(zhiwei))
}

#[event(fetch)]
async fn fetch(
req: HttpRequest,
env: Env,
ctx: Context,
) -> WorkerResult<axum::http::Response<axum::body::Body>> {
console_error_panic_hook::set_once();
Ok(router().call(req).await?)
}

pub async fn root() -> &'static str {
"Hello World!"
}

pub async fn zhiwei() -> &'static str {
"Hello Zhiwei!"
}
fn router() -> Router {
Router::new()
.route("/", get(root))
.route("/zhiwei", get(zhiwei))
}

#[event(fetch)]
async fn fetch(
req: HttpRequest,
env: Env,
ctx: Context,
) -> WorkerResult<axum::http::Response<axum::body::Body>> {
console_error_panic_hook::set_once();
Ok(router().call(req).await?)
}

pub async fn root() -> &'static str {
"Hello World!"
}

pub async fn zhiwei() -> &'static str {
"Hello Zhiwei!"
}
This is work I got, but I can't guarantee it's the most ideal way
Jeroen
Jeroen3mo ago
ahhh yu're using axum, doesn't quite apply for me But I figured a few minutes ago that I can use a String as well, but I have to manually type the Response instead of using the built-in one I turned off the computer though, will try and remember to share for the next victim
Want results from more Discord servers?
Add your server