Skip to content

Handlers that serves jpg / static image not returning correct image  #630

@isaurav0

Description

@isaurav0

I want lambda function to serve png/jpg image using golang.

Steps To Reproduce
Here's go.mod file.

module github.com/someone/downloader

go 1.18

require github.com/aws/aws-lambda-go v1.36.1

main.go looks like:

package main

import (
	"context"
	"encoding/base64"
	"io/ioutil"
	"net/http"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

func handler(ctx context.Context, request events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {

	url := "https://en.meming.world/images/en/a/a1/My_Time_Has_Come.jpg"

	// download image as save it as imageBytes
	response, err := http.Get(url)
	if err != nil {
		return nil, nil
	}
	defer response.Body.Close()

	imageBytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, nil
	}

	// convert to base64 string
	imageBase64 := base64.StdEncoding.EncodeToString(imageBytes)

	// send back response
	return &events.APIGatewayProxyResponse{
		StatusCode: http.StatusOK,
		Headers: map[string]string{
			"Content-Type":                 "image/png",
			"Access-Control-Allow-Origin":  "*",
			"Access-Control-Allow-Headers": "Content-Type",
		},
		Body:            imageBase64,
		IsBase64Encoded: true,
	}, nil
}

func main() {
	lambda.Start(handler)
}

I expect it to return this image.
image

But I'm getting a weird image with rectangular box instead.
image

netlify dev is the command I'm using to run it locally.

I was told it relates to this issue in a stackoverflow post that i made.

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: bugcode to address defects in shipped code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions