Skip to content
Snippets Groups Projects
Select Git revision
  • 34f2caf5168fabeb85b11df5176900f586bd5a08
  • main default protected
  • v1.298.0
  • v1.297.0
  • v1.296.0
  • v1.295.0
  • v1.294.0
  • v1.293.0
  • v1.292.0
  • v1.291.0
  • v1.290.0
  • v1.289.0
  • v1.288.0
  • v1.287.0
  • v1.286.0
  • v1.285.0
  • v1.284.0
  • v1.283.0
  • v1.282.0
  • v1.281.0
  • v1.280.0
  • v1.279.0
22 results

errors.go

Blame
  • 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
    		}