Skip to content
Snippets Groups Projects
Select Git revision
  • 9cd8cc8a5a97344d90d30c3b3ebad842e5ccf9f3
  • 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

api.go

Blame
  • api.go 4.07 KiB
    package api
    
    import (
    	"fmt"
    	"net/http"
    	"os"
    	"regexp"
    	"time"
    
    	"github.com/aws/aws-lambda-go/events"
    	"github.com/aws/aws-lambda-go/lambda"
    	"gitlab.com/uafrica/go-utils/errors"
    	"gitlab.com/uafrica/go-utils/logger"
    	"gitlab.com/uafrica/go-utils/service"
    )
    
    //New creates the API with the specified routes keys on [path][method]
    //value could be any of the handler function signatures supported by the api.Router
    //requestIDHeaderKey is defined in the response header to match the requestID from the request
    func New(requestIDHeaderKey string, routes map[string]map[string]interface{}) Api {
    	env := os.Getenv("ENVIRONMENT") //todo: support config loading for local dev and env for lambda in prod
    	if env == "" {
    		env = "dev"
    	}
    	if requestIDHeaderKey == "" {
    		requestIDHeaderKey = "request-id"
    	}
    
    	router, err := NewRouter(routes)
    	if err != nil {
    		panic(fmt.Sprintf("cannot create router: %+v", err))
    	}
    
    	return Api{
    		ILogger:            logger.New().WithFields(map[string]interface{}{"env": env}),
    		env:                env,
    		router:             router,
    		requestIDHeaderKey: requestIDHeaderKey,
    		checks:             []check{},
    		crashReporter:      defaultCrashReporter{},
    		auditor:            noAudit{},
    	}
    }
    
    type Api struct {
    	logger.ILogger     //for logging outside of context
    	env                string
    	router             Router
    	requestIDHeaderKey string
    
    	//options:
    	localPort     int //==0 for lambda, >0 for http.ListenAndServe
    	crashReporter ICrashReporter
    	cors          ICORS
    	dbConn        service.IDatabaseConnector
    	checks        []check
    	auditor       IAuditor
    }
    
    //checks are executed at the start of each request
    //to stop processing, return an error, preferably with an HTTP status code (see errors.HTTP(...))
    //all values returned will be logged and added to the context for retrieval by any handler
    //the values are added with the check's name as prefix: "<check.name>_<value.name>"
    //and cannot be changed afterwards
    type IChecker interface {
    	Check(req events.APIGatewayProxyRequest) (values map[string]interface{}, err error)
    }
    
    type check struct {
    	name    string