duanaoreng9355 2019-02-24 14:14
浏览 35
已采纳

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

  • 写回答

1条回答 默认 最新

  • dongshadu4498 2019-02-25 00:20
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?