Select Git revision
-
Cornel Rautenbach authoredCornel Rautenbach authored
lambda.go 9.36 KiB
package api
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"math/rand"
"net/http"
"reflect"
"time"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambdacontext"
"gitlab.com/uafrica/go-utils/errors"
"gitlab.com/uafrica/go-utils/logger"
)
func (api Api) NewContext(baseCtx context.Context, requestID string, request events.APIGatewayProxyRequest) (Context, error) {
serviceContext, err := api.Service.NewContext(baseCtx, requestID, nil)
if err != nil {
return nil, err
}
return &apiContext{
Context: serviceContext,
request: request,
}, nil
}
//this is native handler for lambda passed into lambda.Start()
//to run locally, this is called from app.ServeHTTP()
func (api Api) Handler(baseCtx context.Context, apiGatewayProxyReq events.APIGatewayProxyRequest) (res events.APIGatewayProxyResponse, err error) {
res = events.APIGatewayProxyResponse{
StatusCode: http.StatusInternalServerError,
Body: "undefined response",
Headers: map[string]string{},
}
// Replace the proxy resource with the path, has some edge cases but works for our current API implementation
// Edge case being that if have path params then specify those routes explicitly
if apiGatewayProxyReq.Resource == "/{proxy+}" {
apiGatewayProxyReq.Resource = apiGatewayProxyReq.Path
}
//get request-id from HTTP headers (used when making internal service calls)
//if not defined in header, get the AWS request id from the AWS context
requestID, ok := apiGatewayProxyReq.Headers[api.requestIDHeaderKey]
if !ok || requestID == "" {
if lambdaContext, ok := lambdacontext.FromContext(baseCtx); ok && lambdaContext != nil {
requestID = lambdaContext.AwsRequestID
}
}
// service context invoke the starters and could fail, e.g. if cannot connect to db
Ctx, err = api.NewContext(baseCtx, requestID, apiGatewayProxyReq)
if err != nil {
return res, err
}
//report handler crashes
if api.crashReporter != nil {
defer api.crashReporter.Catch(Ctx)
}
defer func() {
//set CORS headers on every response
if api.cors != nil {
for n, v := range api.cors.CORS() {