This commit is contained in:
crusader 2017-11-29 10:01:48 +09:00
parent 1cdf24971c
commit ce8a4781f8

View File

@ -20,10 +20,12 @@ func New(sh ServerHandler) Server {
type Server interface { type Server interface {
Start() error Start() error
Stop() Stop()
Serve() error Context() ServerContext
} }
type server struct { type server struct {
ctx ServerContext
sh ServerHandler sh ServerHandler
listener net.Listener listener net.Listener
@ -44,17 +46,17 @@ func (s *server) Start() error {
panic("Server: server is already running. Stop it before starting it again") panic("Server: server is already running. Stop it before starting it again")
} }
var err error var err error
if s.listener, err = s.sh.Listen(); nil != err { s.ctx = s.sh.ServerContext()
return err
}
if err = s.sh.Init(); nil != err { if err = s.sh.Init(s.ctx); nil != err {
logging.Logger().Panic(fmt.Sprintf("Server: Initialization of server has been failed %v", err)) logging.Logger().Panic(fmt.Sprintf("Server: Initialization of server has been failed %v", err))
} }
s.stopChan = make(chan struct{}) if s.listener, err = s.sh.Listen(s.ctx); nil != err {
return err
}
s.sh.OnStart() s.stopChan = make(chan struct{})
s.stopWg.Add(1) s.stopWg.Add(1)
go handleServer(s) go handleServer(s)
@ -75,17 +77,12 @@ func (s *server) Stop() {
logging.Logger().Info(fmt.Sprintf("Server[%s] is stopped", s.sh.GetName())) logging.Logger().Info(fmt.Sprintf("Server[%s] is stopped", s.sh.GetName()))
} }
func (s *server) Serve() error {
if err := s.Start(); err != nil {
return err
}
s.stopWg.Wait()
return nil
}
func handleServer(s *server) { func handleServer(s *server) {
defer s.stopWg.Done() defer s.stopWg.Done()
logging.Logger().Info(fmt.Sprintf("Server[%s] is started", s.sh.GetName()))
s.sh.OnStart(s.ctx)
var conn net.Conn var conn net.Conn
var err error var err error
var stopping atomic.Value var stopping atomic.Value