updated cli

This commit is contained in:
marvzhang
2021-04-27 17:37:29 +08:00
parent cefe4c7343
commit 820334753a
3 changed files with 48 additions and 26 deletions

View File

@@ -14,18 +14,16 @@ import (
"github.com/spf13/viper"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
type Api struct {
BaseApp
app *gin.Engine
srv *http.Server
}
func (app *Api) Init() {
func (app *Api) init() {
// initialize config
_ = app.initModule("config", config.InitConfig)
@@ -48,29 +46,27 @@ func (app *Api) Init() {
_ = app.initModuleWithApp("routes", routes.InitRoutes)
}
func (app *Api) Run() {
func (app *Api) run() {
host := viper.GetString("server.host")
port := viper.GetString("server.port")
address := net.JoinHostPort(host, port)
srv := &http.Server{
app.srv = &http.Server{
Handler: app.app,
Addr: address,
}
go func() {
if err := srv.ListenAndServe(); err != nil {
if err != http.ErrServerClosed {
log.Error("run server error:" + err.Error())
} else {
log.Info("server graceful down")
}
if err := app.srv.ListenAndServe(); err != nil {
if err != http.ErrServerClosed {
log.Error("run server error:" + err.Error())
} else {
log.Info("server graceful down")
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
ctx2, cancel := context.WithTimeout(context.Background(), 20*time.Second)
}
}
func (app *Api) stop() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := srv.Shutdown(ctx2); err != nil {
if err := app.srv.Shutdown(ctx); err != nil {
log.Error("run server error:" + err.Error())
}
}

View File

@@ -4,24 +4,49 @@ import (
"fmt"
"github.com/apex/log"
"github.com/crawlab-team/go-trace"
"os"
"os/signal"
"syscall"
)
type App interface {
Init()
Run()
init()
run()
stop()
}
type BaseApp struct {
}
func (app *BaseApp) Init() {
func (app *BaseApp) init() {
panic("implement me")
}
func (app *BaseApp) Run() {
func (app *BaseApp) run() {
panic("implement me")
}
func (app *BaseApp) stop() {
panic("implement me")
}
func (app *BaseApp) start() {
app.init()
go app.run()
app.waitForStop()
app.stop()
}
func (app *BaseApp) Start() {
app.start()
}
func (app *BaseApp) waitForStop() {
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
}
func (app *BaseApp) initModule(name string, fn func() error) (err error) {
if err := fn(); err != nil {
log.Error(fmt.Sprintf("init %s error: %s", name, err.Error()))

View File

@@ -1,6 +1,7 @@
package apps
import (
"github.com/apex/log"
"github.com/crawlab-team/crawlab-core/services"
)
@@ -8,12 +9,12 @@ type Handler struct {
BaseApp
}
func (app *Handler) Init() {
func (app *Handler) init() {
_ = app.initModule("task-service", services.InitTaskService)
}
func (app *Handler) Run() {
panic("implement me")
func (app *Handler) run() {
log.Info("handler has started")
}
func NewHandler() *Handler {