github.com/lovung/GoCleanArchitecture@v0.0.0-20210302152432-50d91fd29f9f/cmd/services/core/service.go (about)

     1  package main
     2  
     3  import (
     4  	"os"
     5  	"os/signal"
     6  
     7  	"github.com/lovung/GoCleanArchitecture/app/config"
     8  	"github.com/lovung/GoCleanArchitecture/app/external/api"
     9  	"github.com/lovung/GoCleanArchitecture/pkg/logger"
    10  
    11  	"github.com/gin-gonic/gin"
    12  	"github.com/urfave/cli/v2"
    13  )
    14  
    15  type application struct {
    16  	cfg    *config.Config
    17  	engine *gin.Engine
    18  }
    19  
    20  func (s *application) start() error {
    21  	interrupt := make(chan os.Signal, 1)
    22  	signal.Notify(interrupt, os.Interrupt)
    23  
    24  	s.initDBConnection(s.cfg.MySQL)
    25  	s.initJWTSession(s.cfg.JWTSecret)
    26  
    27  	s.engine = api.Restful(s.cfg)
    28  
    29  	go func() {
    30  		if err := s.engine.Run(":" + s.cfg.HTTPServer.Port); err != nil {
    31  			panic(err)
    32  		}
    33  	}()
    34  
    35  	<-interrupt
    36  
    37  	s.stopping()
    38  
    39  	return nil
    40  }
    41  
    42  // stopping will stop running job or release resources the server was used
    43  func (s *application) stopping() {
    44  	logger.Debug("server stopped")
    45  }
    46  
    47  func newService(ctx *cli.Context) *application {
    48  	s := &application{}
    49  	s.loadConfig(ctx)
    50  
    51  	logger.Init(s.cfg.LogLevel == string(logger.DebugLevel))
    52  	logger.SetLevel(s.cfg.LogLevel)
    53  	return s
    54  }
    55  
    56  func (s *application) loadConfig(ctx *cli.Context) {
    57  	conf := &config.Config{
    58  		Env: ctx.String(EnvFlag.Name),
    59  		HTTPServer: config.ServerCfg{
    60  			Port:    ctx.String(HTTPPortFlag.Name),
    61  			Timeout: ctx.Duration(HTTPTimeoutFlag.Name),
    62  		},
    63  		MySQL: config.MySQL{
    64  			ConnectionString: ctx.String(MYSQLConnFlag.Name),
    65  			Host:             ctx.String(MYSQLHostFlag.Name),
    66  			Port:             ctx.String(MySQLPortFlag.Name),
    67  			User:             ctx.String(MySQLUserFlag.Name),
    68  			Password:         ctx.String(MySQLPasswordFlag.Name),
    69  			DB:               ctx.String(MySQLDatabaseFlag.Name),
    70  			MaxOpenConns:     ctx.Int(MySQLMaxOpenConnsFlag.Name),
    71  			MaxIdleConns:     ctx.Int(MySQLMaxIdleConnsFlag.Name),
    72  			ConnMaxLifetime:  ctx.Int(MySQLConnMaxLifetimeFlag.Name),
    73  			IsEnabledLog:     ctx.String(LogLevelFlag.Name) == string(logger.DebugLevel),
    74  		},
    75  		LogLevel:         ctx.String(LogLevelFlag.Name),
    76  		JWTSecret:        ctx.String(JWTSecretFlag.Name),
    77  		EnabledProfiling: ctx.Bool(EnabledProfilingFlag.Name),
    78  	}
    79  
    80  	s.cfg = conf
    81  	config.SetConfig(conf)
    82  }