Skip to content

Commit

Permalink
feat: Add handlers (#133)
Browse files Browse the repository at this point in the history
* feat: Support custom handlers when registering

You can add custom handlers (like BasicAuth used in the test) to /metrics.

* refactor: Nicer code to create handlers array
  • Loading branch information
johnoppenheimer authored Jul 27, 2022
1 parent 998932b commit e98b629
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
6 changes: 4 additions & 2 deletions middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,11 @@ func NewWithLabels(labels map[string]string, namespace, subsystem string) *Fiber
}

// RegisterAt will register the prometheus handler at a given URL
func (ps *FiberPrometheus) RegisterAt(app *fiber.App, url string) {
func (ps *FiberPrometheus) RegisterAt(app *fiber.App, url string, handlers ...fiber.Handler) {
ps.defaultURL = url
app.Get(ps.defaultURL, adaptor.HTTPHandler(promhttp.Handler()))

h := append(handlers, adaptor.HTTPHandler(promhttp.Handler()))
app.Get(ps.defaultURL, h...)
}

// Middleware is the actual default middleware implementation
Expand Down
36 changes: 36 additions & 0 deletions middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"testing"

"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/basicauth"
)

func TestMiddleware(t *testing.T) {
Expand Down Expand Up @@ -175,3 +176,38 @@ func TestMiddlewareWithLabels(t *testing.T) {
t.Errorf("got %s; want %s", got, want)
}
}

func TestMiddlewareWithBasicAuth(t *testing.T) {
app := fiber.New()

prometheus := New("basic-auth")
prometheus.RegisterAt(app, "/metrics", basicauth.New(basicauth.Config{
Users: map[string]string{
"prometheus": "password",
},
}))

app.Use(prometheus.Middleware)

app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello World")
})

req := httptest.NewRequest("GET", "/", nil)
resp, _ := app.Test(req, -1)
if resp.StatusCode != 200 {
t.Fail()
}

req = httptest.NewRequest("GET", "/metrics", nil)
resp, _ = app.Test(req, -1)
if resp.StatusCode != 401 {
t.Fail()
}

req.SetBasicAuth("prometheus", "password")
resp, _ = app.Test(req, -1)
if resp.StatusCode != 200 {
t.Fail()
}
}

0 comments on commit e98b629

Please sign in to comment.