grafana/pkg/services/ngalert/api/hooks.go
Steve Simpson 9effb9a708
Alerting: Allow hooking into request handler functions. (#67000)
* Alerting: Allow hooking into request handler functions.

Adds a facility to AlertNG for hooking into API handlers, allowing the
replacement of request handlers for specific paths. One of goals of this
approach was to allow hooking as late as possible in the request, e.g.
after all middleware has been applied, to simplfiy usage.

* Update pkg/services/ngalert/api/hooks.go

Co-authored-by: gotjosh <josue.abreu@gmail.com>

* Update pkg/services/ngalert/api/hooks.go

Co-authored-by: gotjosh <josue.abreu@gmail.com>

* Update pkg/services/ngalert/ngalert.go

Co-authored-by: gotjosh <josue.abreu@gmail.com>

* Fixes to review comments

* Fix passing logger in

---------

Co-authored-by: gotjosh <josue.abreu@gmail.com>
2023-04-24 18:18:44 +02:00

44 lines
1.4 KiB
Go

package api
import (
"github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/infra/log"
contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model"
)
type RequestHandlerFunc func(*contextmodel.ReqContext) response.Response
type Hooks struct {
logger log.Logger
hooks map[string]RequestHandlerFunc
}
// NewHooks creates an empty set of request handler hooks. Hooks can be used
// to replace handlers for specific paths.
func NewHooks(logger log.Logger) *Hooks {
return &Hooks{
logger: logger,
hooks: make(map[string]RequestHandlerFunc),
}
}
// Add creates a new request hook for a path, causing requests to the path to
// be handled by the hook function, and not the original handler.
func (h *Hooks) Set(path string, hook RequestHandlerFunc) {
h.logger.Info("setting hook override for the specified route", "path", path)
h.hooks[path] = hook
}
// Wrap returns a new handler which will intercept paths with hooks configured,
// and invoke the hooked in handler instead. If no hook is configured for a path,
// then the given handler is invoked.
func (h *Hooks) Wrap(next RequestHandlerFunc) RequestHandlerFunc {
return func(req *contextmodel.ReqContext) response.Response {
if hook, ok := h.hooks[req.Context.Req.URL.Path]; ok {
h.logger.Debug("hook defined - invoking new handler", "path", req.Context.Req.URL.Path)
return hook(req)
}
return next(req)
}
}