Home > Backend Development > Golang > How to return HTML from Go Lambda function?

How to return HTML from Go Lambda function?

WBOY
Release: 2024-02-08 21:40:28
forward
818 people have browsed it

如何从 Go Lambda 函数返回 HTML?

php editor Shinichi will answer this question in detail when he introduces how to return HTML from the Go Lambda function. A Go Lambda function is a function that runs in the cloud and returns an HTML page, which is a common requirement for many web developers. In this article, we will explore how to write a Lambda function in Go and return it as an HTML page for consumption by the front end. With the guidance of this article, you will be able to easily implement the function of returning HTML from a Go Lambda function. Let’s get started now!

Question content

I have a go program that provides waveform information in html format when a url is clicked. It runs on a virtual machine with nginx reverse proxy.

I'm trying to move the code to aws lambda but I'm having trouble understanding how to trigger and return the html.

The original code performs its logic and renders the data as template html in the snippet 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)
}
Copy after login

I believe I no longer need the nginx proxy, but instead need to call a lambda function to run my code. So I 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)
}
Copy after login

When I run the aws test, the lba function uses the default json text.

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}
Copy after login

Error occurred during timeout:

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

I'm not sure if the lambda function is ignoring the test, or the function is not returning html in the correct way, or if the lambda function expects json instead of html? Any pointers to help me understand and where I should look?

Solution

No need to run http server on 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)
}
Copy after login

With AWS API Gateway proxy, you 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
}

Copy after login

The above is the detailed content of How to return HTML from Go Lambda function?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template