package service import ( "context" "fmt" "net" "net/http" "time" "mstore/app/handler" "mstore/app/logger" "mstore/app/router" ) const protocol = "tcp" type ServiceParams struct { Handler *handler.Handler } type Service struct { hand *handler.Handler rout *router.Router logg *logger.Logger address string portnum int64 listen net.Listener hsrv *http.Server } func NewService(params *ServiceParams) (*Service, error) { var err error svc := &Service{ hand: params.Handler, } svc.logg = logger.NewLogger("service") return svc, err } func (svc *Service) Build() error { var err error svc.logg.Infof("Service build ") svc.rout = router.NewRouter() svc.rout.Get(PathServiceHello, svc.hand.SendHello) svc.rout.Get(PathFileExists, svc.hand.FileExists) listenAddress := fmt.Sprintf("%s:%d", svc.address, svc.portnum) svc.listen, err = net.Listen(protocol, listenAddress) svc.hsrv = &http.Server{ Handler: svc.rout, } return err } func (svc *Service) Run() error { var err error svc.logg.Infof("Service run") err = svc.hsrv.Serve(svc.listen) if err != nil { return err } return err } func (svc *Service) Stop() { svc.logg.Infof("Service stop") if svc.hsrv != nil { downWaiting := 5 * time.Second ctx, _ := context.WithTimeout(context.Background(), downWaiting) svc.hsrv.Shutdown(ctx) } }