Add a hit counter to our stack #
Okay, our hit counter is ready. Let’s use it in our app. Open cdk-workshop.go
and add
the following highlighted code:
package main
import (
"cdk-workshop/hitcounter"
"github.com/aws/aws-cdk-go/awscdk/v2"
"github.com/aws/aws-cdk-go/awscdk/v2/awslambda"
"github.com/aws/aws-cdk-go/awscdk/v2/awsapigateway"
"github.com/aws/constructs-go/constructs/v10"
"github.com/aws/jsii-runtime-go"
)
type CdkWorkshopStackProps struct {
awscdk.StackProps
}
func NewCdkWorkshopStack(scope constructs.Construct, id string, props *CdkWorkshopStackProps) awscdk.Stack {
var sprops awscdk.StackProps
if props != nil {
sprops = props.StackProps
}
stack := awscdk.NewStack(scope, &id, &sprops)
helloHandler := awslambda.NewFunction(stack, jsii.String("HelloHandler"), &awslambda.FunctionProps{
Code: awslambda.Code_FromAsset(jsii.String("lambda"), nil),
Runtime: awslambda.Runtime_NODEJS_16_X(),
Handler: jsii.String("hello.handler"),
})
hitcounter := hitcounter.NewHitCounter(stack, "HelloHitCounter", &hitcounter.HitCounterProps{
Downstream: helloHandler,
})
awsapigateway.NewLambdaRestApi(stack, jsii.String("Endpoint"), &awsapigateway.LambdaRestApiProps{
Handler: hitcounter.Handler(),
})
return stack
}
func main() {
defer jsii.Close()
app := awscdk.NewApp(nil)
NewCdkWorkshopStack(app, "CdkWorkshopStack", &CdkWorkshopStackProps{})
app.Synth(nil)
}
Notice that we changed our API Gateway handler to hitcounter.Handler()
instead of helloHandler
. This basically means that whenever our endpoint is hit, API
Gateway will route the request to our hit counter handler, which will log the
hit and relay it over to the helloHandler
function. Then, the responses will be
relayed back in the reverse order all the way to the user.
Deploy #
cdk deploy
It might take a little while.
And the output:
CdkWorkshopStack.Endpoint8024A810 = https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/
Test #
Okay, ready to give this a go? (you should, again, see the URL of your API in the output of the “deploy” command).
Use curl
or your web browser to hit your endpoint (we use -i
to show HTTP
response fields and status code):
curl -i https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/
Oh no… seems like something went wrong:
HTTP/2 502 Bad Gateway
...
{"message": "Internal server error"}
Let’s see how to find out what happened and fix it.