github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/service/service.go (about)

     1  package service
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"reflect"
     7  
     8  	"github.com/spf13/cobra"
     9  
    10  	"github.com/johnnyeven/libtools/conf"
    11  	"github.com/johnnyeven/libtools/httplib"
    12  	"github.com/johnnyeven/libtools/service/dockerizier"
    13  )
    14  
    15  // @deprecated
    16  func New(serviceName string) *Service {
    17  	serve := Service{Name: serviceName}
    18  	return &serve
    19  }
    20  
    21  type Service struct {
    22  	Name               string
    23  	AutoMigrate        bool
    24  	envConfigPrefix    string
    25  	outputDockerConfig bool
    26  	help               bool
    27  	cfg                interface{}
    28  }
    29  
    30  func (s *Service) SetEnvConfigPrefix(pre string) {
    31  	s.envConfigPrefix = pre
    32  }
    33  
    34  func (s *Service) ConfP(c interface{}) {
    35  	tpe := reflect.TypeOf(c)
    36  	if tpe.Kind() != reflect.Ptr {
    37  		panic(fmt.Errorf("ConfP pass ptr for setting value"))
    38  	}
    39  	s.cfg = c
    40  	s.Execute()
    41  }
    42  
    43  func (s *Service) Execute() {
    44  	if projectFeature, exists := os.LookupEnv("PROJECT_FEATURE"); exists && projectFeature != "" {
    45  		s.Name = s.Name + "--" + projectFeature
    46  	}
    47  
    48  	command := &cobra.Command{
    49  		Use:   s.Name,
    50  		Short: fmt.Sprintf("%s", s.Name),
    51  		Run: func(cmd *cobra.Command, args []string) {
    52  		},
    53  	}
    54  
    55  	command.PersistentFlags().
    56  		StringVarP(&s.envConfigPrefix, "env-config-prefix", "e", "S", "prefix for env var config")
    57  	command.PersistentFlags().
    58  		BoolVarP(&s.outputDockerConfig, "output-docker-config", "c", true, "output configuration of docker")
    59  	command.PersistentFlags().
    60  		BoolVarP(&s.AutoMigrate, "auto-migrate", "m", os.Getenv("GOENV") == "DEV" || os.Getenv("GOENV") == "TEST", "auto migrate database if need")
    61  	command.PersistentFlags().
    62  		BoolVarP(&s.help, "help", "h", false, "show help")
    63  
    64  	if err := command.Execute(); err != nil {
    65  		fmt.Println(err)
    66  		os.Exit(1)
    67  	}
    68  
    69  	if s.help {
    70  		os.Exit(0)
    71  	}
    72  
    73  	s.conf()
    74  }
    75  
    76  func (s *Service) conf() {
    77  	os.Setenv(EnvVarKeyProjectName, s.Name)
    78  	httplib.SetServiceName(s.Name)
    79  
    80  	envVars := conf.UnmarshalConf(s.cfg, s.envConfigPrefix)
    81  	envVars.Print()
    82  
    83  	if s.outputDockerConfig {
    84  		dockerizier.Dockerize(envVars, s.Name)
    85  	}
    86  }
    87  
    88  var (
    89  	EnvVarKeyProjectName = "PROJECT_NAME"
    90  )