登录
首页 >  Golang >  Go问答

Golang AWS API Gateway 无法识别以字符“e”开头的值

来源:stackoverflow

时间:2024-03-28 21:18:27 233浏览 收藏

从现在开始,努力学习吧!本文《Golang AWS API Gateway 无法识别以字符“e”开头的值》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

问题内容

我正在尝试创建一个连接到 lambda 的 api 网关,该 lambda 使用句柄解析 html 模板,然后返回它,但当我在本地运行它时,甚至在使用 aws 的测试 url 上运行它时,我收到此错误。

{
"errormessage": "invalid character 'e' looking for beginning of value",
"errortype": "syntaxerror"
}

这是我的 sam 模板

awstemplateformatversion: "2010-09-09"
transform: aws::serverless-2016-10-31
description: data-template-renderer
parameters:
  stage:
    type: string
    allowedvalues:
    - dev
    - staging
    - production
    description: environment values
resources:
  # defining the api resource here means we can define the stage name rather than
  # always being forced to have staging/prod. also means we can add a custom domain with
  # to the api gateway within this template if needed. unfortunately there is a side effect
  # where it creates a stage named "stage". this is a known bug and the issue can be
  # found at https://github.com/awslabs/serverless-application-model/issues/191
  datatemplaterendererapi:
    type: aws::serverless::api
    properties:
      name: !sub "${stage}-data-template-renderer"
      stagename: !ref stage
      definitionbody:
        swagger: "2.0"
        basepath: !sub "/${stage}"
        info:
          title: !sub "${stage}-data-template-renderer"
          version: "1.0"
        consumes:
        - application/json
        produces:
        - application/json
        - text/plain
        - application/pdf
        paths:
          /render:
            post:
              x-amazon-apigateway-integration:
                uri:
                  "fn::sub": "arn:aws:apigateway:${aws::region}:lambda:path/2015-03-31/functions/${rendertemplate.arn}/invocations"
                httpmethod: post
                type: aws_proxy
        x-amazon-apigateway-binary-media-types:
        - "*/*"

  rendertemplate:
    type: aws::serverless::function
    properties:
      environment:
        variables:
          env: !ref stage
      runtime: go1.x
      codeuri: build
      handler: render_template
      functionname: !sub 'render_template-${stage}'
      timeout: 30
      tracing: active
      events:
        rendertemplateendpoint:
          type: api
          properties:
            restapiid: !ref datatemplaterendererapi
            path: /render
            method: post
      policies:
      - !ref s3accesspolicy
      - cloudwatchputmetricpolicy: {}

  s3accesspolicy:
    type: aws::iam::managedpolicy
    properties:
      managedpolicyname: data-template-renderer-s3-policy
      policydocument:
        version: "2012-10-17"
        statement:
        - effect: allow
          action: s3:getobject
          resource: !sub "arn:aws:s3:::*"
        - effect: allow
          action: s3:putobject
          resource: !sub "arn:aws:s3:::*"

下面是我用于 lambda 的代码。请原谅,它可能不是您见过的最好的 golang 代码,但对于 golang 来说,我是一个初学者,因为我主要是一名 php 开发人员,但我工作的公司正在创建大量 golang lambda,所以我开始学习一下。

package main

import (
    "bytes"
    "context"
    "encoding/base64"
    "encoding/json"
    "fmt"
    "strings"
    "time"

    "github.com/aymerick/raymond"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
    "github.com/SebastiaanKlippert/go-wkhtmltopdf"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
)

var sess *session.Session

func init() {
    // Setup AWS S3 Session (build once use every function)
    sess = session.Must(session.NewSession(&aws.Config{
        Region: aws.String("us-east-1"),
    }))
}

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

type TemplateRendererRequest struct {
    Template string `json:"template"`
    Bucket string `json:"bucket"`
    Type string `json:"type"`
    Data map[string]interface{} `json:"data"`
}

type EmailResponse struct {
    Email string `json:"email"`
}

func handleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Unmarshal json request body into a TemplateRendererRequest struct that mimics the json payload
    requestData := TemplateRendererRequest{}
    err := json.Unmarshal([]byte(request.Body), &requestData)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body: fmt.Errorf("Error: %s ", err.Error()).Error(),
            StatusCode: 400,
            Headers: map[string]string{
                "Content-Type": "text/plain",
            },
        }, err
    }

    // Get the template object from S3
    result, err := s3.New(sess).GetObject(&s3.GetObjectInput{
        Bucket: aws.String(requestData.Bucket),
        Key:    aws.String(requestData.Template),
    })
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body: fmt.Errorf("Error: %s ", err.Error()).Error(),
            StatusCode: 400,
            Headers: map[string]string{
                "Content-Type": "text/plain",
            },
        }, err
    }
    defer result.Body.Close()

    // The S3 Object Body is of type io.ReadCloser
    // below we create a bytes buffer and then convert it to a string so we can use it later
    buf := new(bytes.Buffer)
    buf.ReadFrom(result.Body)
    templateString := buf.String()

    // Parse template through Handlebars library
    parsedTemplate, err := parseTemplate(templateString, requestData)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body: fmt.Errorf("Error: %s ", err.Error()).Error(),
            StatusCode: 400,
            Headers: map[string]string{
                "Content-Type": "text/plain",
            },
        }, err
    }

    switch requestData.Type {
    case "pdf":
        return handlePDFRequest(parsedTemplate, requestData)
    default:
        return handleEmailRequest(parsedTemplate)
    }
}

func handleEmailRequest(parsedTemplate string) (events.APIGatewayProxyResponse, error) {
    // Put email parsed template in a struct to return in the form of JSON
    emailResponse := EmailResponse{
        Email: parsedTemplate,
    }
    // JSON encode the emailResponse
    response, err := JSONMarshal(emailResponse)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body: fmt.Errorf("Error: %s ", err.Error()).Error(),
            StatusCode: 400,
            Headers: map[string]string{
                "Content-Type": "text/plain",
            },
        }, err
    }

    return events.APIGatewayProxyResponse{
        Body: string(response),
        StatusCode: 200,
        Headers: map[string]string{
            "Content-Type": "application/json",
        },
    }, nil
}

func parseTemplate(templateString string, request TemplateRendererRequest) (string, error) {
    result, err := raymond.Render(templateString, request.Data)

    return result, err
}

func handlePDFRequest(parsedTemplate string, requestData TemplateRendererRequest) (events.APIGatewayProxyResponse, error) {
    pdfBytes, err := GeneratePDF(parsedTemplate)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body: fmt.Errorf("Error: %s ", err.Error()).Error(),
            StatusCode: 400,
            Headers: map[string]string{
                "Content-Type": "text/plain",
            },
        }, err
    }

    keyNameParts := strings.Split(requestData.Template, "/")
    keyName := keyNameParts[len(keyNameParts)-1]
    pdfName := fmt.Sprintf("%s_%s.pdf", keyName, time.Now().UTC().Format("20060102150405"))
    _, err = s3.New(sess).PutObject(&s3.PutObjectInput{
        Bucket: aws.String(requestData.Bucket),
        Key:    aws.String(pdfName),
        Body:   bytes.NewReader(pdfBytes),
    })

    b64Pdf := base64.StdEncoding.EncodeToString(pdfBytes)
    return events.APIGatewayProxyResponse{
        Body: b64Pdf,
        StatusCode: 200,
        Headers: map[string]string{
            "Content-Type": "application/pdf",
        },
        IsBase64Encoded: true,
    }, nil
}

func GeneratePDF(templateString string) ([]byte, error) {
    pdfg, err := wkhtmltopdf.NewPDFGenerator()
    if err != nil {
        return nil, err
    }

    // Pass S3 Object body (as reader io.Reader) directly into wkhtmltopdf
    pdfg.AddPage(wkhtmltopdf.NewPageReader(strings.NewReader(templateString)))

    // Create PDF document in internal buffer
    if err := pdfg.Create(); err != nil {
        return nil, err
    }

    // Return PDF as bytes array
    return pdfg.Bytes(), nil
}

// https://stackoverflow.com/questions/28595664/how-to-stop-json-marshal-from-escaping-and
func JSONMarshal(t interface{}) ([]byte, error) {
    buffer := &bytes.Buffer{}
    encoder := json.NewEncoder(buffer)
    encoder.SetEscapeHTML(false)
    err := encoder.Encode(t)
    return buffer.Bytes(), err
}

我尝试到处搜索解决方案,但找不到为什么我会收到这个非常奇怪的错误,这不是很有帮助。 感谢您抽出时间并提供帮助


解决方案


感谢 @anzel 为我指明了正确的方向,我决定查看 request.body ,似乎通过将 */* 添加到 api 网关二进制媒体类型,现在即使请求也以编码形式出现你瞧,第一个字母确实是 e,正如消息所说。

所以我改变了这个:

// unmarshal json request body into a templaterendererrequest struct that mimics the json payload
    requestdata := templaterendererrequest{}
    err := json.unmarshal([]byte(request.body), &requestdata)
    if err != nil {
        return events.apigatewayproxyresponse{
            body: fmt.errorf("error: %s ", err.error()).error(),
            statuscode: 400,
            headers: map[string]string{
                "content-type": "text/plain",
            },
        }, err
    }

对此:

// unmarshal json request body into a templaterendererrequest struct that mimics the json payload
    requestdata := templaterendererrequest{}

    b64string, _ := base64.stdencoding.decodestring(request.body)
    rawin := json.rawmessage(b64string)
    bodybytes, err := rawin.marshaljson()
    if err != nil {
        return events.apigatewayproxyresponse{
            body: fmt.errorf("error: %s ", err.error()).error(),
            statuscode: 400,
            headers: map[string]string{
                "content-type": "text/plain",
            },
        }, err
    }

    jsonmarshalerr := json.unmarshal(bodybytes, &requestdata)
    if jsonmarshalerr != nil {
        return events.apigatewayproxyresponse{
            body: fmt.errorf("error: %s ", jsonmarshalerr.error()).error(),
            statuscode: 400,
            headers: map[string]string{
                "content-type": "text/plain",
            },
        }, jsonmarshalerr
    }

根据我在网上看到的内容,您也可以更改此设置:

rawin := json.rawmessage(b64string)
bodybytes, err := rawin.marshaljson()

对此:

[]byte(b64String)

当我现在执行 curl 请求并将其输出到文件时,我可以正确获取 pdf。

以上就是《Golang AWS API Gateway 无法识别以字符“e”开头的值》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>