Looking at the Using global state section in the official AWS Lambda function handler in Go doc https://docs.aws.amazon.com/lambda/latest/dg/golang-handler.html
suggests to initialise all global state in func init()
i.e. Any package level vars which we want to share across multiple lambda invocations go here.
And my understanding is that this initialisation is done once per lambda container start (i.e cold start).
My question is, is it possible to do the same using func main()
instead of func init()
.
Using func init()
basically makes my handler function (func LambdaHandler
) non unit-testable due to side-effects from func init()
running.
Moving the func init()
code to func main()
seems to solve this easily.
Are there any side effects to using func main()
vs func init()
Code Example
Using func init()
package main
import (
"log"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/aws"
)
var invokeCount = 0
var myObjects []*s3.Object
func init() {
svc := s3.New(session.New())
input := &s3.ListObjectsV2Input{
Bucket: aws.String("examplebucket"),
}
result, _ := svc.ListObjectsV2(input)
myObjects = result.Contents
}
func LambdaHandler() (int, error) {
invokeCount = invokeCount + 1
log.Print(myObjects)
return invokeCount, nil
}
func main() {
lambda.Start(LambdaHandler)
}
vs
Using func main()
package main
import (
"log"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/aws"
)
var invokeCount = 0
var myObjects []*s3.Object
func LambdaHandler() (int, error) {
invokeCount = invokeCount + 1
log.Print(myObjects)
return invokeCount, nil
}
func main() {
svc := s3.New(session.New())
input := &s3.ListObjectsV2Input{
Bucket: aws.String("examplebucket"),
}
result, _ := svc.ListObjectsV2(input)
myObjects = result.Contents
lambda.Start(LambdaHandler)
}
main
either. Put any code you want to test in a function that you can call from a test and pass in the required dependencies for that code. – Abrasionmain
orinit
. I want to test the code inLambdaHandler
. But this is not possible if there is afunc init()
as it causes side-effects when I try to test it – Callupmain
is no more testable thaninit
. If you need runtime error handling, then put it in main. Wether you useinit
ormain
to setup some data structures is up to you, but I prefer to avoidinit
formain
packages. – AbrasionLambdaHandler
– Callup