github.com/yoogoc/kratos-scaffold@v0.0.0-20240402032722-a538b3c18955/project_generator/resources/cmd.main.go.tmpl (about)

     1  {{- /*gotype: github.com/yoogoc/kratos-scaffold/project_generator.CmdTmpl*/ -}}
     2  package main
     3  
     4  import (
     5  	"fmt"
     6  	"{{.AppPkgPath}}/internal/conf"
     7  	ilog "{{.AppPkgPath}}/internal/log"
     8  	"os"
     9  
    10  	"github.com/go-kratos/kratos/v2/config"
    11  	"github.com/go-kratos/kratos/v2/config/env"
    12  	"github.com/go-kratos/kratos/v2/config/file"
    13  
    14  	"github.com/spf13/cobra"
    15  )
    16  
    17  // go build -ldflags "-X main.Version=x.y.z"
    18  var (
    19  	// Name is the name of the compiled software.
    20  	Name = "{{.ServiceName}}"
    21  	// Version is the version of the compiled software.
    22  	Version string
    23  
    24  	flagconf string
    25  )
    26  
    27  type RootCommand cobra.Command
    28  
    29  func main() {
    30  	cmd, _, _ := initApp(ilog.NameString(Name), ilog.VersionString(Version))
    31  
    32  	if err := cmd.Execute(); err != nil {
    33  		_, _ = fmt.Fprintln(os.Stderr, err)
    34  		os.Exit(1)
    35  	}
    36  }
    37  
    38  func newConf(rootCmd *RootCommand) *conf.Bootstrap {
    39  	flags := (*cobra.Command)(rootCmd).PersistentFlags()
    40  	flags.StringVarP(&flagconf, "config", "c", "./configs", "config path, eg: --config=config.yaml")
    41  	var bc conf.Bootstrap
    42  	_ = flags.Parse(os.Args[1:])
    43  
    44  	c := config.New(
    45  		config.WithSource(
    46  			file.NewSource(flagconf),
    47  			env.NewSource("kratos_"),
    48  		),
    49  	)
    50  	if err := c.Load(); err != nil {
    51  		panic(err)
    52  	}
    53  	if err := c.Scan(&bc); err != nil {
    54  		panic(err)
    55  	}
    56  	return &bc
    57  }
    58  
    59  func newDataConf(bc *conf.Bootstrap) *conf.Data {
    60  	return bc.Data
    61  }
    62  
    63  func newLogConf(bc *conf.Bootstrap) *conf.Log {
    64  	return bc.Log
    65  }
    66  
    67  func newServerConf(bc *conf.Bootstrap) *conf.Server {
    68  	return bc.Server
    69  }
    70  
    71  func newRootCmd() *RootCommand {
    72  	root := &RootCommand{
    73  		Short:              "assign service",
    74  		Long:               "assign service",
    75  		FParseErrWhitelist: cobra.FParseErrWhitelist{UnknownFlags: true},
    76  		Run: func(cmd *cobra.Command, args []string) {
    77  			_ = cmd.Help()
    78  		},
    79  	}
    80  
    81  	return root
    82  }
    83  
    84  {{- if .IsBff }}
    85  func newCmd(root *RootCommand, server *ServerCommand) *cobra.Command {
    86  {{- else }}
    87  func newCmd(root *RootCommand, server *ServerCommand, migrate *MigrateCommand) *cobra.Command {
    88  {{- end }}
    89  	(*cobra.Command)(root).AddCommand(
    90  		(*cobra.Command)(server),
    91  		(*cobra.Command)(migrate),
    92  	)
    93  	return (*cobra.Command)(root)
    94  }