aws-lambda-events icon indicating copy to clipboard operation
aws-lambda-events copied to clipboard

AlbTargetGroupResponse automatically base64 encodes data

Open WhyNotHugo opened this issue 3 years ago • 6 comments

I'm using this to return some image data from a lambda:

    let resp = AlbTargetGroupResponse {
        status_code: 200,
        body: Some(Body::Binary(buf)),
        headers: HeaderMap::new(),
        is_base64_encoded: true,
        multi_value_headers: HeaderMap::new(),
        status_description: Some(String::from("200 OK")),
    };

It appears that when using body: Some(Body::Binary(buf)), this library automatically encodes the payload in base64.

In this case, is_base64_encoded should be set to true. However, it might make sense to drop the is_base64_encoded field entirely, and auto-generate that based on the type of body:

  • If body is Body::Text -> is_base64_encoded = false.
  • If body is Body::Binary -> is_base64_encoded = true.
  • If body is Body::Empty -> irrelevant...?

Given that most of the code around this is auto-generated, I'm not sure if this is even possible.

Are there any fields that are auto-generated based on other's value? Do you think my suggestion makes sense, or is it simpler to just add a note in the docs explaining that binary content is always base64 encoded?

WhyNotHugo avatar Nov 09 '21 17:11 WhyNotHugo

Hmmm, I'll have to think about this. I think we can support this case but it will take some refactoring.

LegNeato avatar Nov 10 '21 17:11 LegNeato

Somewhat related: If when returning Some(Body::Empty) from a lambda the ALB then yields 502. Returning None works though. If I understand the source correctly, Some(Body::Empty) is converted to body: null, but None merely results in the field being omitted when serialising.

I'm using this in a helper for now (I takes body: Body as input):

    let (is_base64_encoded, body) = match body {
        Body::Empty => (false, None), // Body::Empty results in ALB returning 502.
        Body::Text(_) => (false, Some(body)),
        Body::Binary(_) => (true, Some(body)),
    };

WhyNotHugo avatar Nov 10 '21 17:11 WhyNotHugo

Is the go code correct in this case? Does it have omitempty?

LegNeato avatar Nov 10 '21 20:11 LegNeato

It does not. I've sent a patch via https://github.com/aws/aws-lambda-go/pull/408.

WhyNotHugo avatar Nov 12 '21 17:11 WhyNotHugo

Go code is now correct: https://github.com/aws/aws-lambda-go/pull/408

I think it's a matter of re-generating the auto-generated code?

WhyNotHugo avatar Apr 11 '22 21:04 WhyNotHugo

The Alb code is no longer under the generator, so we can make any adjustments we'd like to improve the experience of using that type, like the automatic encoding selection that you mention in the description.

Feel free to make changes in that module: https://github.com/LegNeato/aws-lambda-events/blob/master/aws_lambda_events/src/alb/mod.rs

calavera avatar Apr 11 '22 22:04 calavera