add RegisterCheck web server option for internal health checks

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2019-12-05 17:15:35 +03:00
parent 18cf025056
commit a957e90ca8
3 changed files with 24 additions and 1 deletions

View File

@ -25,6 +25,9 @@ type Options struct {
RegisterTTL time.Duration RegisterTTL time.Duration
RegisterInterval time.Duration RegisterInterval time.Duration
// RegisterCheck runs a check function before registering the service
RegisterCheck func(context.Context) error
Server *http.Server Server *http.Server
Handler http.Handler Handler http.Handler
@ -62,6 +65,10 @@ func newOptions(opts ...Option) Options {
o(&opt) o(&opt)
} }
if opt.RegisterCheck == nil {
opt.RegisterCheck = DefaultRegisterCheck
}
return opt return opt
} }
@ -225,3 +232,10 @@ func StaticDir(d string) Option {
o.StaticDir = d o.StaticDir = d
} }
} }
// RegisterCheck run func before registry service
func RegisterCheck(fn func(context.Context) error) Option {
return func(o *Options) {
o.RegisterCheck = fn
}
}

View File

@ -123,6 +123,13 @@ func (s *service) register() error {
srv := s.genSrv() srv := s.genSrv()
srv.Endpoints = s.srv.Endpoints srv.Endpoints = s.srv.Endpoints
s.srv = srv s.srv = srv
// use RegisterCheck func before register
if err := s.opts.RegisterCheck(s.opts.Context); err != nil {
log.Logf("Server %s-%s register check error: %s", s.opts.Name, s.opts.Id, err)
return err
}
return r.Register(s.srv, registry.RegisterTTL(s.opts.RegisterTTL)) return r.Register(s.srv, registry.RegisterTTL(s.opts.RegisterTTL))
} }

View File

@ -2,6 +2,7 @@
package web package web
import ( import (
"context"
"net/http" "net/http"
"time" "time"
@ -32,7 +33,8 @@ var (
DefaultRegisterInterval = time.Second * 30 DefaultRegisterInterval = time.Second * 30
// static directory // static directory
DefaultStaticDir = "html" DefaultStaticDir = "html"
DefaultRegisterCheck = func(context.Context) error { return nil }
) )
// NewService returns a new web.Service // NewService returns a new web.Service