1
0
mirror of https://github.com/go-micro/go-micro.git synced 2025-11-23 21:44:41 +02:00

feat(web): add start and stop functions to the web (#2519)

This commit is contained in:
JellyTony
2022-07-01 15:06:27 +08:00
committed by GitHub
parent 87c96bc4d0
commit 96576a612a
2 changed files with 34 additions and 5 deletions

View File

@@ -34,6 +34,7 @@ type service struct {
running bool running bool
static bool static bool
exit chan chan error exit chan chan error
ex chan bool
} }
func newService(opts ...Option) Service { func newService(opts ...Option) Service {
@@ -42,6 +43,7 @@ func newService(opts ...Option) Service {
opts: options, opts: options,
mux: http.NewServeMux(), mux: http.NewServeMux(),
static: true, static: true,
ex: make(chan bool),
} }
s.srv = s.genSrv() s.srv = s.genSrv()
return s return s
@@ -90,7 +92,7 @@ func (s *service) genSrv() *registry.Service {
} }
} }
func (s *service) run(exit chan bool) { func (s *service) run() {
s.RLock() s.RLock()
if s.opts.RegisterInterval <= time.Duration(0) { if s.opts.RegisterInterval <= time.Duration(0) {
s.RUnlock() s.RUnlock()
@@ -104,7 +106,7 @@ func (s *service) run(exit chan bool) {
select { select {
case <-t.C: case <-t.C:
s.register() s.register()
case <-exit: case <-s.ex:
t.Stop() t.Stop()
return return
} }
@@ -440,6 +442,32 @@ func (s *service) Init(opts ...Option) error {
return nil return nil
} }
func (s *service) Start() error {
if err := s.start(); err != nil {
return err
}
if err := s.register(); err != nil {
return err
}
// start reg loop
go s.run()
return nil
}
func (s *service) Stop() error {
// exit reg loop
close(s.ex)
if err := s.deregister(); err != nil {
return err
}
return s.stop()
}
func (s *service) Run() error { func (s *service) Run() error {
if err := s.start(); err != nil { if err := s.start(); err != nil {
return err return err
@@ -467,8 +495,7 @@ func (s *service) Run() error {
} }
// start reg loop // start reg loop
ex := make(chan bool) go s.run()
go s.run(ex)
ch := make(chan os.Signal, 1) ch := make(chan os.Signal, 1)
if s.opts.Signal { if s.opts.Signal {
@@ -489,7 +516,7 @@ func (s *service) Run() error {
} }
// exit reg loop // exit reg loop
close(ex) close(s.ex)
if err := s.deregister(); err != nil { if err := s.deregister(); err != nil {
return err return err

View File

@@ -16,6 +16,8 @@ type Service interface {
Options() Options Options() Options
Handle(pattern string, handler http.Handler) Handle(pattern string, handler http.Handler)
HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
Start() error
Stop() error
Run() error Run() error
} }