3

I've written a small lambda function and deployed to AWS using the serverless framework. It provides a single function that returns a png file.

  • When the resource is opened in a browser it correctly loads a png.

  • When requested with curl curl "https://******.execute-api.us-east-1.amazonaws.com/dev/image.png" it produces a base64 encoded version of the image.

  • When I request on the command line with Accept header curl -H "Accept: image/png" https://******.execute-api.us-east-1.amazonaws.com/dev/image.png" it produces a binary image/png version of the image.

How do I manipulate the request to the API gateway so that all requests have "Accept: image/png" set on them regardless of origin? Or is there another way to ensure that the response will always be binary rather than base64?

Source Code

The handler code loads a png image from disk and then returns a response object with a base64 encoded output of the image.

// handler.js
'use strict';

const fs = require('fs');
const image = fs.readFileSync('./1200x600.png');

module.exports = {
    image: async (event) => {
        return {
            statusCode: 200,
            headers: {
                "Content-Type": "image/png",
            },
            isBase64Encoded: true,
            body: image.toString('base64'),
        };
    },
};

The serverless configuration sets up the function and uses the "serverless-apigw-binary" and "serverless-apigwy-binary" plugins to set content handling and binary mime types for the response.

# serverless.yml
service: serverless-png-facebook-test

provider:
  name: aws
  runtime: nodejs8.10

functions:
  image:
    handler: handler.image
    memorySize: 128
    events:
      - http:
          path: image.png
          method: get
          contentHandling: CONVERT_TO_BINARY

plugins:
  - serverless-apigw-binary
  - serverless-apigwy-binary

custom:
  apigwBinary:
    types:
      - 'image/*'

package.json

{
  "name": "serverless-png-facebook-test",
  "version": "1.0.0",
  "main": "handler.js",
  "license": "MIT",
  "dependencies": {
    "serverless-apigw-binary": "^0.4.4",
    "serverless-apigwy-binary": "^1.0.0"
  }
}
onmylemon
  • 724
  • 8
  • 25
  • Specifically for the portion of your question asking for the header overriding via API Gateway, you can refer this manual: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-override-request-response-parameters.html#apigateway-override-request-response-parameters-override-request – vahdet May 04 '19 at 13:54
  • The main idea was to be able to do this with serverless. – onmylemon Jun 18 '19 at 11:49

0 Answers0