github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/loader/api_loader.go (about) 1 package loader 2 3 import ( 4 "github.com/hellofresh/janus/pkg/api" 5 "github.com/hellofresh/janus/pkg/middleware" 6 obs "github.com/hellofresh/janus/pkg/observability" 7 "github.com/hellofresh/janus/pkg/plugin" 8 "github.com/hellofresh/janus/pkg/proxy" 9 log "github.com/sirupsen/logrus" 10 "go.opencensus.io/tag" 11 ) 12 13 // APILoader is responsible for loading all apis form a datastore and configure them in a register 14 type APILoader struct { 15 register *proxy.Register 16 } 17 18 // NewAPILoader creates a new instance of the api manager 19 func NewAPILoader(register *proxy.Register) *APILoader { 20 return &APILoader{register: register} 21 } 22 23 // RegisterAPIs load application middleware 24 func (m *APILoader) RegisterAPIs(cfgs []*api.Definition) { 25 for _, spec := range cfgs { 26 m.RegisterAPI(spec) 27 } 28 } 29 30 // RegisterAPI register an API Definition in the register 31 func (m *APILoader) RegisterAPI(def *api.Definition) { 32 logger := log.WithField("api_name", def.Name) 33 logger.Debug("Starting RegisterAPI") 34 35 active, err := def.Validate() 36 if false == active && err != nil { 37 logger.WithError(err).Error("Validation errors") 38 } 39 40 if false == def.Active { 41 logger.Warn("API is not active, skipping...") 42 active = false 43 } 44 45 if active { 46 routerDefinition := proxy.NewRouterDefinition(def.Proxy) 47 48 for _, plg := range def.Plugins { 49 l := logger.WithField("name", plg.Name) 50 51 isValid, err := plugin.ValidateConfig(plg.Name, plg.Config) 52 if !isValid || err != nil { 53 l.WithError(err).Error("Plugin configuration is invalid") 54 } 55 56 if plg.Enabled { 57 l.Debug("Plugin enabled") 58 59 setup, err := plugin.DirectiveAction(plg.Name) 60 if err != nil { 61 l.WithError(err).Error("Error loading plugin") 62 continue 63 } 64 65 err = setup(routerDefinition, plg.Config) 66 if err != nil { 67 l.WithError(err).Error("Error executing plugin") 68 } 69 } else { 70 l.Debug("Plugin not enabled") 71 } 72 } 73 74 if len(def.Proxy.Hosts) > 0 { 75 routerDefinition.AddMiddleware(middleware.NewHostMatcher(def.Proxy.Hosts).Handler) 76 } 77 78 // Add middleware to insert tags to context 79 tags := []tag.Mutator{ 80 tag.Insert(obs.KeyListenPath, def.Proxy.ListenPath), 81 } 82 routerDefinition.AddMiddleware(middleware.NewStatsTagger(tags).Handler) 83 84 m.register.Add(routerDefinition) 85 logger.Debug("API registered") 86 } else { 87 logger.WithError(err).Warn("API URI is invalid or not active, skipping...") 88 } 89 }