Added support for hooks to customize behavior.

This commit is contained in:
Travis Reeder
2016-08-09 22:34:28 -07:00
parent 72a6d3aa5b
commit 8558d13f07
23 changed files with 324 additions and 42 deletions

View File

@@ -3,17 +3,25 @@ package server
import (
"path"
"golang.org/x/net/context"
"github.com/Sirupsen/logrus"
"github.com/gin-gonic/gin"
"github.com/iron-io/functions/api/ifaces"
"github.com/iron-io/functions/api/models"
titancommon "github.com/iron-io/titan/common"
)
// Would be nice to not have this is a global, but hard to pass things around to the
// handlers in Gin without it.
var Api *Server
type Server struct {
Router *gin.Engine
Config *models.Config
Datastore models.Datastore
Router *gin.Engine
Config *models.Config
Datastore models.Datastore
AppListeners []ifaces.AppListener
SpecialHandlers []ifaces.SpecialHandler
}
func New(ds models.Datastore, config *models.Config) *Server {
@@ -25,6 +33,49 @@ func New(ds models.Datastore, config *models.Config) *Server {
return Api
}
// AddAppListener adds a listener that will be notified on App changes.
func (s *Server) AddAppListener(listener ifaces.AppListener) {
s.AppListeners = append(s.AppListeners, listener)
}
func (s *Server) FireBeforeAppUpdate(ctx context.Context, app *models.App) error {
for _, l := range s.AppListeners {
err := l.BeforeAppUpdate(ctx, app)
if err != nil {
return err
}
}
return nil
}
func (s *Server) FireAfterAppUpdate(ctx context.Context, app *models.App) error {
for _, l := range s.AppListeners {
err := l.AfterAppUpdate(ctx, app)
if err != nil {
return err
}
}
return nil
}
func (s *Server) AddSpecialHandler(handler ifaces.SpecialHandler) {
s.SpecialHandlers = append(s.SpecialHandlers, handler)
}
func (s *Server) UseSpecialHandlers(ginC *gin.Context) error {
c := &SpecialHandlerContext{
server: s,
ginContext: ginC,
}
for _, l := range s.SpecialHandlers {
err := l.Handle(c)
if err != nil {
return err
}
}
return nil
}
func extractFields(c *gin.Context) logrus.Fields {
fields := logrus.Fields{"action": path.Base(c.HandlerName())}
for _, param := range c.Params {
@@ -33,9 +84,11 @@ func extractFields(c *gin.Context) logrus.Fields {
return fields
}
func (s *Server) Run() {
func (s *Server) Run(ctx context.Context) {
s.Router.Use(func(c *gin.Context) {
c.Set("log", logrus.WithFields(extractFields(c)))
ctx, _ := titancommon.LoggerWithFields(ctx, extractFields(c))
c.Set("ctx", ctx)
c.Next()
})
@@ -66,11 +119,12 @@ func bindHandlers(engine *gin.Engine) {
apps.PUT("/routes/*route", handleRouteUpdate)
apps.DELETE("/routes/*route", handleRouteDelete)
}
}
engine.Any("/r/:app/*route", handleRunner)
engine.NoRoute(handleRunner)
// This final route is used for extensions, see Server.Add
engine.NoRoute(handleSpecial)
}
func simpleError(err error) *models.Error {