Golang Lambda中的快速重新发送响应

I have golang lambda that prepares ES request, send it to external system and returns its response. Currently, I haven't found a better approach than an unmarshalling response to interface{}.

func HandleRequest(ctx context.Context, searchRequest SearchRequest) (interface{}, error) {
    // ... some data preparation and client initalisation
    resp, err := ctxhttp.Post(ctx, &client, url, "application/json", buffer)
    if err != nil {
        return "", err
    }
    var k interface{}
    all, err := ioutil.ReadAll(resp.Body)
    err = json.Unmarshal(all, &k)
    return k, err
}

I'm not sure it is the fastest and the most performant way to forward response due to that extra ReadAll and Unmarshall. Is there a more performant approach? I looked at events.APIGatewayProxyResponse{}, but body in it - string and same manipulations are needed

You can handle the response in many different way

  • If lambda implements additional search response handling, it might be worth defining the response data type contract with respective marshaling/unmarshaling and additional handling logic.

  • If lambda functionality is to only proxy response from ES search, you may just passed search response payload ([]byte) directly to APIGatewayProxyResponse.Body as []byte and may need to base64 if the payload has binary data.

Code:

func handleRequest(ctx context.Context, apiRequest events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    request, err := newSearchRequest(apiRequest)
    if err != nil {
        return handleError(err)
    }
    responseBody, err := proxySearch(ctx, request)
    if err != nil {
        return handleError(err)
    }
    return events.APIGatewayProxyResponse{
        StatusCode: http.StatusOK,
        Body:       string(responseBody),
    }, nil
}

func proxySearch(ctx context.Context, searchRequest SearchRequest) ([]byte, error) {
    // ... some data preparation and client initalisation
    resp, err := ctxhttp.Post(ctx, &client, url, "application/json", buffer)
    if err != nil {
        return nil, err
    }
    responseBody, err := ioutil.ReadAll(resp.Body)
    return responseBody, err
}