Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

healthcheck: implement GetOrRegisterHealthcheck and NewRegisteredHealthcheck #240

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions healthcheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ type Healthcheck interface {
Unhealthy(error)
}

// GetOrRegisterHealthcheck returns an existing Healthcheck or
// constructs and registers a new StandardHealthcheck.
func GetOrRegisterHealthcheck(name string, r Registry, f func(Healthcheck)) Healthcheck {
if nil == r {
r = DefaultRegistry
}
return r.GetOrRegister(name, func() Healthcheck { return NewHealthcheck(f) }).(Healthcheck)
}

// NewHealthcheck constructs a new Healthcheck which will use the given
// function to update its status.
func NewHealthcheck(f func(Healthcheck)) Healthcheck {
Expand All @@ -17,6 +26,16 @@ func NewHealthcheck(f func(Healthcheck)) Healthcheck {
return &StandardHealthcheck{nil, f}
}

// NewRegisteredHealthcheck constructs and registers a new StandardHealthcheck.
func NewRegisteredHealthcheck(name string, r Registry, f func(Healthcheck)) Healthcheck {
c := NewHealthcheck(f)
if nil == r {
r = DefaultRegistry
}
r.Register(name, c)
return c
}

// NilHealthcheck is a no-op.
type NilHealthcheck struct{}

Expand Down
17 changes: 17 additions & 0 deletions healthcheck_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package metrics

import (
"errors"
"testing"
)

func TestGetOrRegisterHealthcheck(t *testing.T) {
r := NewRegistry()
check := func(h Healthcheck) {
h.Unhealthy(errors.New("foo"))
}
NewRegisteredHealthcheck("foo", r, check).Check()
if h := GetOrRegisterHealthcheck("foo", r, check); h.Error().Error() != "foo" {
t.Fatal(h)
}
}