How to return HTML from a Go Lambda function?

huangapple go评论82阅读模式
英文:

How to return HTML from a Go Lambda function?

问题

我有一个Go程序,当访问URL时,以HTML格式提供波浪信息。它在一个带有nginx反向代理的虚拟机上运行。

我正在尝试将代码迁移到AWS Lambda,但我不太明白如何触发和返回HTML。

原始代码在下面的片段中执行逻辑并将数据呈现为模板HTML。

func indexHandler(w http.ResponseWriter, r *http.Request) {
	GetWeather()
	GetSurf()
	CheckSurf(ForecastGroup)
	p := CodCallPage{Title: "Swell Forecast", RunTime: htmlRunDate, DailyHtmlData: DailyMatchingSwells}
	codcallTemplateInit.Execute(w, p)
}

func main() {
	http.HandleFunc("/", indexHandler)
	http.ListenAndServe(":8000", nil)
}

我相信我不再需要nginx代理,需要调用lambda函数来运行我的代码。所以我将代码更改为以下内容。

func indexHandler(w http.ResponseWriter, r *http.Request) {
	GetWeather()
	GetSurf()
	CheckSurf(ForecastGroup)
	p := CodCallPage{Title: "Swell Forecast", RunTime: htmlRunDate, DailyHtmlData: DailyMatchingSwells}
	codcallTemplateInit.Execute(w, p)
}

func handler(ctx context.Context, request events.APIGatewayProxyRequest) error {
	log.Println("Via Lambda !!")
	http.HandleFunc("/", indexHandler)
}

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

当我运行带有默认JSON文本的AWS测试,lambda函数会超时并报错。

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

错误信息如下:

{
  "errorMessage": "2023-06-08T08:43:13.714Z d6e2acc0-b1da-4e92-820b-63f8f5050947 Task timed out after 15.01 seconds"
}

我不确定lambda函数是否忽略了测试,或者函数没有以正确的方式返回HTML,或者lambda函数是否期望JSON而不是HTML?请给我一些建议,帮助我理解并指导我应该查看哪些地方。

英文:

I have a Go program that serves wave information in html format when the a URL is hit. It was running on a VM with a nginx reverse proxy.

I am trying to move the code to AWS Lambda, but I am struggling to understand how to trigger and return the html.

The original code did its logic and presented is data as template HTML in the snip below.

func indexHandler(w http.ResponseWriter, r *http.Request) {
	GetWeather()
	GetSurf()
	CheckSurf(ForecastGroup)
	p := CodCallPage{Title: "Swell Forecast", RunTime: htmlRunDate, DailyHtmlData: DailyMatchingSwells}
	codcallTemplateInit.Execute(w, p)
}

func main() {
	http.HandleFunc("/", indexHandler)
	http.ListenAndServe(":8000", nil)
}

I believe I no longer need the nginx proxy and need to invoke the lambda function to run my code. So I have changed the code to the following.

func indexHandler(w http.ResponseWriter, r *http.Request) {
	GetWeather()
	GetSurf()
	CheckSurf(ForecastGroup)
	p := CodCallPage{Title: "Swell Forecast", RunTime: htmlRunDate, DailyHtmlData: DailyMatchingSwells}
	codcallTemplateInit.Execute(w, p)
}

func handler(ctx context.Context, request events.APIGatewayProxyRequest) error {
	log.Println("Via Lambda !!")
	http.HandleFunc("/", indexHandler)
}

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

When I run the AWS test, lamba function with the default JSON text.

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

It gives an error as it times out:

{
  "errorMessage": "2023-06-08T08:43:13.714Z d6e2acc0-b1da-4e92-820b-63f8f5050947 Task timed out after 15.01 seconds"
}

I'm not sure if the test is being ignored by the lambda function or the function isn't returning the HTML in the correct way, or if the lambda function is expecting JSON rather than HTML ? Any pointers to help me understand and where I should look, please?

答案1

得分: 2

不需要在 Lambda 函数上运行 HTTP 服务器。这段代码应该可以工作。

func indexHandler(ctx context.Context, req events.APIGatewayProxyRequest) (string, error)  {
        GetWeather()
        GetSurf()
        CheckSurf(ForecastGroup)
        p := CodCallPage{Title: "Swell Forecast", RunTime: htmlRunDate, DailyHtmlData: DailyMatchingSwells}
        var res bytes.Buffer
        if err := codcallTemplateInit.Execute(&res, p); err != nil {
          return "", err 
        }
        return res.String(), nil
}


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

使用 AWS API 网关代理,你需要返回 events.APIGatewayProxyResponse,所以 indexHandler 将会有所不同。

func indexHandler(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error)  {
        GetWeather()
        GetSurf()
        CheckSurf(ForecastGroup)
        p := CodCallPage{Title: "Swell Forecast", RunTime: htmlRunDate, DailyHtmlData: DailyMatchingSwells}
        var res bytes.Buffer
        if err := codcallTemplateInit.Execute(&res, p); err != nil {
          return events.APIGatewayProxyResponse{StatusCode: 400, Body: err.Error()}, err 
        }
        return events.APIGatewayProxyResponse{Body: res.String(), StatusCode: 200}, nil
}
英文:

There's no need to run an http server on a lambda function. this code should work

func indexHandler(ctx context.Context, req events.APIGatewayProxyRequest) (string, error)  {
        GetWeather()
        GetSurf()
        CheckSurf(ForecastGroup)
        p := CodCallPage{Title: "Swell Forecast", RunTime: htmlRunDate, DailyHtmlData: DailyMatchingSwells}
        var res bytes.Buffer
        if err := codcallTemplateInit.Execute(&res, p); err != nil {
          return "", err 
        }
        return res.String(), nil
}


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

Using AWS API gateway proxy you'll need to return return events.APIGatewayProxyResponse so indexHandler will be different.

func indexHandler(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error)  {
        GetWeather()
        GetSurf()
        CheckSurf(ForecastGroup)
        p := CodCallPage{Title: "Swell Forecast", RunTime: htmlRunDate, DailyHtmlData: DailyMatchingSwells}
        var res bytes.Buffer
        if err := codcallTemplateInit.Execute(&res, p); err != nil {
          return events.APIGatewayProxyResponse{StatusCode: 400, Body: err.Error()}, err 
        }
        return events.APIGatewayProxyResponse{Body: res.String(), StatusCode: 200}, nil
}



</details>



huangapple
  • 本文由 发表于 2023年6月8日 17:01:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76430232.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定