Search code examples
goaws-lambdaaws-api-gateway

Return Json From lambda Go in ApiGateway


Im trying to make this work, what i want is to get json as output from lambda when called from API gateway with some nested json.

This is what i expect, { "data": {"username":"Random User","Age":20}", "message": "This is sample" } but im getting escaped json { "data": "\n\t{\n\t\t\"username\":\"Random User\",\n\t\t\"Age\":20\n\t}", "message": "This is sample" }

the sample code which im trying

package main

import (
    "encoding/json"
    "log"
    "net/http"

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

type Response struct {
    StatusCode int               `json:"statusCode"`
    Headers    map[string]string `json:"headers"`
    Body       string            `json:"body"`
}

type RequestBody struct {
    Data    any    `json:"data"`
    Message string `json:"message"`
}

const (
    data string = `
    {
        "username":"Random User",
        "Age":20
    }`
)

func EventHandler(request events.APIGatewayProxyRequest) (Response, error) {
    response := Response{}
    log.Println(request.Headers)
    body := RequestBody{Data: data, Message: "This is sample"}
    b, _ := json.Marshal(body)
    response.Body = string(b)
    response.StatusCode = http.StatusOK
    log.Println("Before Return")
    return response, nil
}

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


Solution

  • This is because to marshaled (encoded as JSON) a string that already contains a JSON object. Instead, try this:

    var data = map[string]any {
            "username":"Random User",
            "Age":20
        }
    

    Or you can also do:

        body := RequestBody{Data: json.RawMessage(data), Message: "This is sample"}