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?
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
}