Skip to content

Commit 41aadd4

Browse files
committedNov 29, 2021
将命令行参数解析功能放到cmd package
1 parent e15b2bc commit 41aadd4

11 files changed

+179
-56
lines changed
 

‎cmd/app_command.go

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package cmd
2+
3+
import (
4+
"github.com/urfave/cli/v2"
5+
)
6+
7+
var runFlags = []cli.Flag{
8+
&cli.StringFlag{
9+
Name: "log-path",
10+
Usage: "billing log file path",
11+
},
12+
}
13+
14+
//AppCommand 项目命令根节点
15+
func AppCommand() *cli.App {
16+
return &cli.App{
17+
Name: "billing",
18+
Usage: "billing server command line tool",
19+
EnableBashCompletion: true,
20+
Flags: runFlags,
21+
Action: runUpCommand,
22+
Commands: []*cli.Command{
23+
UpCommand(),
24+
StopCommand(),
25+
ShowUsersCommand(),
26+
},
27+
}
28+
}

‎cmd/doc.go

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
// Package cmd 包含了所有的命令行相关功能
2+
package cmd

‎cmd/show_users.go

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package cmd
2+
3+
import (
4+
"fmt"
5+
"github.com/liuguangw/billing_go/services/billing"
6+
"github.com/urfave/cli/v2"
7+
)
8+
9+
// ShowUsersCommand 打印用户列表状态的命令
10+
func ShowUsersCommand() *cli.Command {
11+
return &cli.Command{
12+
Name: "show_users",
13+
Usage: "show users list status",
14+
Action: runShowUsersCommand,
15+
}
16+
}
17+
18+
//runShowUsersCommand 打印用户列表状态
19+
func runShowUsersCommand(c *cli.Context) error {
20+
//初始化server
21+
server, err := billing.NewServer()
22+
if err != nil {
23+
return err
24+
}
25+
fmt.Println("show users log ...")
26+
return server.ShowUsers()
27+
}

‎cmd/stop.go

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package cmd
2+
3+
import (
4+
"fmt"
5+
"github.com/liuguangw/billing_go/services/billing"
6+
"github.com/urfave/cli/v2"
7+
)
8+
9+
// StopCommand 停止server的命令
10+
func StopCommand() *cli.Command {
11+
return &cli.Command{
12+
Name: "stop",
13+
Usage: "stop the billing server",
14+
Action: runStopCommand,
15+
}
16+
}
17+
18+
//runStopCommand 停止billing服务
19+
func runStopCommand(c *cli.Context) error {
20+
//初始化server
21+
server, err := billing.NewServer()
22+
if err != nil {
23+
return err
24+
}
25+
fmt.Println("stoping billing server ...")
26+
if err := server.Stop(); err != nil {
27+
return err
28+
}
29+
fmt.Println("stop command sent successfully")
30+
return nil
31+
}

‎cmd/up.go

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package cmd
2+
3+
import (
4+
"errors"
5+
"github.com/liuguangw/billing_go/services"
6+
"github.com/liuguangw/billing_go/services/billing"
7+
"github.com/urfave/cli/v2"
8+
"os"
9+
"runtime"
10+
)
11+
12+
// UpCommand 运行server的命令
13+
func UpCommand() *cli.Command {
14+
upFlags := append(runFlags, &cli.BoolFlag{
15+
Name: "daemon",
16+
Aliases: []string{"d"},
17+
Usage: "daemon mode, run server at background",
18+
})
19+
return &cli.Command{
20+
Name: "up",
21+
Usage: "run the billing server",
22+
Flags: upFlags,
23+
Action: runUpCommand,
24+
}
25+
}
26+
27+
//runUpCommand 运行billing服务
28+
func runUpCommand(c *cli.Context) error {
29+
isDaemon := c.IsSet("daemon")
30+
logPath := c.String("log-path")
31+
//后台模式
32+
if isDaemon {
33+
if runtime.GOOS == "windows" {
34+
return errors.New("daemon mode is not supported on windows")
35+
}
36+
return services.RunBillingAtBackground(os.Args[0], logPath)
37+
}
38+
//初始化server
39+
server, err := billing.NewServer()
40+
if err != nil {
41+
return err
42+
}
43+
server.Run(logPath)
44+
return nil
45+
}

‎go.mod

+3
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,16 @@ go 1.17
55
require (
66
github.com/go-sql-driver/mysql v1.6.0
77
github.com/mattn/go-colorable v0.1.12
8+
github.com/urfave/cli/v2 v2.3.0
89
go.uber.org/zap v1.19.1
910
golang.org/x/text v0.3.7
1011
gopkg.in/yaml.v2 v2.4.0
1112
)
1213

1314
require (
15+
github.com/cpuguy83/go-md2man/v2 v2.0.1 // indirect
1416
github.com/mattn/go-isatty v0.0.14 // indirect
17+
github.com/russross/blackfriday/v2 v2.1.0 // indirect
1518
go.uber.org/atomic v1.9.0 // indirect
1619
go.uber.org/multierr v1.7.0 // indirect
1720
golang.org/x/sys v0.0.0-20211124211545-fe61309f8881 // indirect

‎go.sum

+11-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1+
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
12
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
23
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
4+
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
5+
github.com/cpuguy83/go-md2man/v2 v2.0.1 h1:r/myEWzV9lfsM1tFLgDyu0atFtJ1fXn261LKYj/3DxU=
6+
github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
37
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
48
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
59
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -10,8 +14,6 @@ github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORN
1014
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
1115
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
1216
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
13-
github.com/mattn/go-colorable v0.1.11 h1:nQ+aFkoE2TMGc0b68U2OKSexC+eq46+XwZzWXHRmPYs=
14-
github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
1517
github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40=
1618
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
1719
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
@@ -20,10 +22,16 @@ github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
2022
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
2123
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
2224
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
25+
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
26+
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
27+
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
28+
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
2329
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
2430
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
2531
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
2632
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
33+
github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M=
34+
github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
2735
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
2836
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
2937
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
@@ -52,8 +60,6 @@ golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7w
5260
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
5361
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
5462
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
55-
golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1 h1:kwrAHlwJ0DUBZwQ238v+Uod/3eZ8B2K5rYsUHBQvzmI=
56-
golang.org/x/sys v0.0.0-20211117180635-dee7805ff2e1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
5763
golang.org/x/sys v0.0.0-20211124211545-fe61309f8881 h1:TyHqChC80pFkXWraUUf6RuB5IqFdQieMLwwCJokV2pc=
5864
golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
5965
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
@@ -71,6 +77,7 @@ golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8T
7177
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
7278
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
7379
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
80+
gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
7481
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
7582
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
7683
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=

‎main.go

+3-40
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,14 @@
11
package main
22

33
import (
4-
"fmt"
5-
"github.com/liuguangw/billing_go/services"
6-
"github.com/liuguangw/billing_go/services/billing"
4+
"github.com/liuguangw/billing_go/cmd"
75
"log"
86
"os"
9-
"runtime"
107
)
118

129
func main() {
13-
// ./billing up -d
14-
// 使用上面的命令时, 程序会在后台运行(支持类unix系统, 不支持windows)
15-
if len(os.Args) > 2 {
16-
if os.Args[1] == "up" && os.Args[2] == "-d" && runtime.GOOS != "windows" {
17-
if err := services.RunBillingAtBackground(os.Args[0]); err != nil {
18-
log.Fatalln(err)
19-
}
20-
return
21-
}
22-
}
23-
//初始化server
24-
server, err := billing.NewServer()
25-
if err != nil {
10+
appCommand := cmd.AppCommand()
11+
if err := appCommand.Run(os.Args); err != nil {
2612
log.Fatalln(err)
2713
}
28-
//命令
29-
if len(os.Args) > 1 {
30-
commandStr := os.Args[1]
31-
//处理./billing stop
32-
if commandStr == "stop" {
33-
fmt.Println("stoping billing server ...")
34-
if err := server.Stop(); err != nil {
35-
log.Fatalln(err)
36-
}
37-
fmt.Println("stop command sent successfully")
38-
return
39-
}
40-
//./billing show_users
41-
if commandStr == "show_users" {
42-
fmt.Println("show users log ...")
43-
if err := server.ShowUsers(); err != nil {
44-
log.Fatalln(err)
45-
}
46-
return
47-
}
48-
}
49-
//启动
50-
server.Run()
5114
}

‎services/billing/init_logger.go

+22-9
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,15 @@ import (
1010
)
1111

1212
// initLogger 初始化日志系统
13-
func (s *Server) initLogger() error {
14-
//当前程序文件的绝对路径
15-
mainAppPath, err := filepath.Abs(os.Args[0])
16-
if err != nil {
17-
return err
13+
func (s *Server) initLogger(logFilePath string) error {
14+
if logFilePath == "" {
15+
//使用默认日志路径
16+
defaultPath, err := defaultLogFilePath()
17+
if err != nil {
18+
return err
19+
}
20+
logFilePath = defaultPath
1821
}
19-
//程序目录
20-
appDir := filepath.Dir(mainAppPath)
21-
//打开日志文件
22-
logFilePath := filepath.Join(appDir, "billing.log")
2322
fileFlag := os.O_APPEND | os.O_CREATE | os.O_WRONLY
2423
logFile, err := os.OpenFile(logFilePath, fileFlag, 0644)
2524
if err != nil {
@@ -61,3 +60,17 @@ func (s *Server) initLogger() error {
6160
s.logger = zap.New(core, zap.AddStacktrace(zapcore.WarnLevel))
6261
return nil
6362
}
63+
64+
//默认的日志文件路径
65+
func defaultLogFilePath() (string, error) {
66+
//当前程序文件的绝对路径
67+
mainAppPath, err := filepath.Abs(os.Args[0])
68+
if err != nil {
69+
return "", err
70+
}
71+
//程序目录
72+
appDir := filepath.Dir(mainAppPath)
73+
//日志文件
74+
logFilePath := filepath.Join(appDir, "billing.log")
75+
return logFilePath, nil
76+
}

‎services/billing/run.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,16 @@ import (
1010
)
1111

1212
// Run 运行billing
13-
func (s *Server) Run() {
13+
func (s *Server) Run(logFilePath string) {
1414
//初始化日志系统
15-
if err := s.initLogger(); err != nil {
15+
if err := s.initLogger(logFilePath); err != nil {
1616
log.Fatalln("init logger failed: " + err.Error())
1717
}
1818
//退出前,执行清理任务
1919
defer s.clean()
2020
//输出build信息
2121
services.ShowVersionInfo(s.logger)
22+
s.logger.Info("log file: " + s.logFile.Name())
2223
//初始化tcp Listener
2324
if err := s.initListener(); err != nil {
2425
s.logger.Fatal("init listener failed: " + err.Error())

‎services/run_background.go

+4-1
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,11 @@ import (
77
)
88

99
// RunBillingAtBackground 在后台运行程序
10-
func RunBillingAtBackground(billingPath string) error {
10+
func RunBillingAtBackground(billingPath, logFilePath string) error {
1111
cmd := exec.Command(billingPath)
12+
if logFilePath != "" {
13+
cmd.Args = append(cmd.Args, "--log-path", logFilePath)
14+
}
1215
// 重定向输出文件
1316
outFile, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0644)
1417
if err != nil {

0 commit comments

Comments
 (0)
Please sign in to comment.