1. 字符串处理
1.1 去除空白符
// this data still needs to be parsed
lines = strings.Split(r.Output, "\n")
for i = range lines {
lines[i] = strings.TrimSpace(lines[i])
}
// trim away empty lines
lines = lines[1 : len(lines)-1]
2. 自定义命令一(cobra)
├─cmd
│ ├─main.go
cmd/main.go
package main
import (
"fmt"
"os"
"time"
"go.uber.org/zap"
"github.com/spf13/cobra"
)
var (
LogAction string
Date string
logger *zap.Logger
)
func InitLogger() {
logger, _ = zap.NewProduction()
}
// cli 命令基于 https://github.com/spf13/cobra 封装
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "Cli",
Short: "A brief description of your application",
Long: `调用方法:
1.进入项目根目录(Ginkeleton)。
2.执行 go run cmd/main.go -h //可以查看使用指南
3.执行 go run cmd/main.go -A update // 通过 Action 动作执行相应的命令`,
Run: func(cmd *cobra.Command, args []string) {
//args 参数表示非flag(也叫作位置参数),该参数默认会作为一个数组存储。
//fmt.Println(args)
start(LogAction, Date) // 调用业务函数
},
}
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
InitLogger()
RootCmd.Flags().StringVarP(&LogAction, "logAction", "A", "insert", "-A 指定参数动作,例如:-A insert ")
RootCmd.Flags().StringVarP(&Date, "date", "D", time.Now().Format("2006-01-02"), "-D 指定日期,例如:-D 2021-09-13")
}
// 自定义业务函数
func start(actionName, Date string) {
switch actionName {
case "insert":
logger.Info("insert 参数执行对应业务逻辑,Date参数值:" + Date)
case "update":
logger.Info("update 参数执行对应业务逻辑,Date参数值:" + Date)
}
}
func main() {
Execute()
defer logger.Sync()
}
自定义命令二(cli)
main.go
package main
import (
"fmt"
"github.com/urfave/cli/v2"
)
func main() {
myApp := cli.NewApp()
myApp.Name = "kcptun"
myApp.Usage = "client(with SMUX)"
myApp.Version = "1.0"
myApp.Flags = []cli.Flag{
cli.StringFlag{
Name: "localaddr,l", # 参数名
Value: ":12948", # 默认值
Usage: "local listen address", # 用法介绍
Required: true, # 必要参数
DefaultText :"random", # 提示信息中显示的默认值,覆盖Value值,更于理解
},
cli.StringFlag{
Name: "remoteaddr, r",
Value: "vps:29900",
Usage: "kcp server address",
},
cli.StringFlag{
Name: "key",
Value: "it's a secrect",
Usage: "pre-shared secret between client and server",
EnvVar: "KCPTUN_KEY", # 从环境变量读取
},
}
myApp.Action = func(c *cli.Context) error {
localaddr := c.String("localaddr")
remoteAddr := c.String("remoteaddr")
key := c.String("key")
runMyFunc(localaddr, remoteAddr, key)
}
err := myApp.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func runMyFunc(localaddr, remoteAddr, key string){
fmt.Printf("hello")
fmt.Printf(localaddr, remoteAddr, key)
}