Select Git revision
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