Select Git revision
context.go 6.52 KiB
package api
import (
"encoding/json"
"reflect"
"strings"
"github.com/aws/aws-lambda-go/events"
"gitlab.com/uafrica/go-utils/errors"
"gitlab.com/uafrica/go-utils/reflection"
"gitlab.com/uafrica/go-utils/service"
)
type Context interface {
service.Context
Request() events.APIGatewayProxyRequest
}
var contextInterfaceType = reflect.TypeOf((*Context)(nil)).Elem()
type apiContext struct {
service.Context
request events.APIGatewayProxyRequest
}
func (ctx apiContext) Request() events.APIGatewayProxyRequest {
return ctx.request
}
//todo: change to be a ctx method that defer to log so it does not have to be called explicitly
//it should also capture metrics for the handler and automaticlaly write the audit record,
//(but still allow for audit to be suppressed may be in some cases)
func (ctx *apiContext) LogAPIRequestAndResponse(res events.APIGatewayProxyResponse, err error) {
fields := map[string]interface{}{
"path": ctx.request.Path,
"method": ctx.request.HTTPMethod,
"status_code": res.StatusCode,
"api_gateway_request_id": ctx.RequestID(),
}
if ctx.request.HTTPMethod == "GET" {
fields["req-query"] = ctx.request.QueryStringParameters
}
statusOK := res.StatusCode >= 200 && res.StatusCode <= 299
if err != nil || !statusOK {
fields["error"] = err
fields["req-body"] = ctx.request.Body
fields["req-query"] = ctx.request.QueryStringParameters
fields["res-body"] = res.Body
}
ctx.Context.WithFields(fields).Infof("Request & Response: err=%+v", err)
}
//allocate struct for params, populate it from the URL parameters then validate and return the struct
func (ctx apiContext) GetRequestParams(paramsStructType reflect.Type) (interface{}, error) {
paramValues := map[string]interface{}{}
for n, v := range ctx.request.QueryStringParameters {
paramValues[n] = v
}
paramsStructValuePtr := reflect.New(paramsStructType)
for i := 0; i < paramsStructType.NumField(); i++ {
f := paramsStructType.Field(i)
n := (strings.SplitN(f.Tag.Get("json"), ",", 2))[0]
if n == "" {
n = strings.ToLower(f.Name)
}
if n == "" || n == "-" {
continue
}