How to extract login and password from a HTTP Post using http::request::Request?

I am working on a simple AWS Lambda function and I need to implement a user login.

I am not sure how do I actually get the different bits and pieces from the body. What is the safe way of getting user_name and password coming from a HTTP POST (I guess application/x-www-form-urlencoded).

fn user_login(req: Request, ctx: Context) -> Result<Response<Body>, HandlerError> { 
    let body = req.body();
}

The request crate doesn't currently provide any functionality for processing request/response bodies - Request and Response both have a type parameter which defines what calling .body() will return. It's up to the framework built on top of http to define what these body types actually are.

So this raises the question, why does your Request not have a type parameter? Is that pseudo-code/a typo, or does it actually work in your program?

If the latter, I think you're not actually working with the http types, but something wrapping them. The lambda_http crate, perhaps? The fact you're using HandlerError makes me think that might be the case.

If you are using lambda_http, then Request is actually a type alias for http::Request<lambda_http::Body>, so calling .body() on it will return this type. You can match on that type to extract the body data.

That said, the body data will still be in string/byte form - you'll need to parse it somehow. A quick Google brought up serde_urlencoded, which might be helpful.

EDIT: Actually, lambda_http provides that functionality out of the box if you bring the RequestExt trait into scope - you can then do request.payload() to deserialize the body. This uses serde_json/serde_urlencoded under the hood.

2 Likes

@17cupsofcoffee thank you very much for the detailed explanation!

1 Like

No problem, was fun digging to find out how the types slotted together :smiley:

1 Like