urfave/cli go 命令解析开发

虞展
2023-12-01

go 标准库 flag 作为命令参数以及够绝大部门应用使用,但是复杂应用,如独立程序,很多子命令用来交互的,这时候,flag 就显得力不从心了,这时候就需要寻找一块表现力丰富命令参数程序来够使用。

安装:go get github.com/urfave/cli   或者: go get gopkg.in/urfave/cli.v2

 但是如何合理使用参数,使程序更有意义,就要就讲究顺序和加载逻辑:

package main

import (
   "fmt"
   "github.com/gin-gonic/gin"
   "gopkg.in/urfave/cli.v2"
   "log"
   "os"
   "runtime"
   "strconv"
  "sort“
)
var (
   app = &cli.App{
   Name: "trader",
   Usage: "free quantization for cryptocurrency !", 
   Version : "1.0.0",
   Flags: []cli.Flag {
      &cli.StringFlag{
         Name: "lang",
         Value: "english",
         Usage: "language for display",
      },
      &cli.IntFlag {
         Name: "port, p",
         Value: 8080,
         Usage: "listening web port",
      },
   },
    Commands: []*cli.Command{
      {
         Name:    "complete",
         Aliases: []string{"c"},
         Usage:   "complete a task on the list",
         Action:  func(c *cli.Context) error {
            return nil
         },
      },
      {
         Name:    "add",
         Aliases: []string{"a"},
         Usage:   "add a task to the list",
         Action:  func(c *cli.Context) error {
            return nil
         },
      },
},
})
func init() {
   app.Action = rundeamon
   app.Before = func(ctx *cli.Context) error {
      runtime.GOMAXPROCS(runtime.NumCPU())
      return nil
   }
   app.After = func(c *cli.Context) error {
      fmt.Println("app After")
      return nil
   }
   sort.Sort(cli.FlagsByName(app.Flags))   
   sort.Sort(cli.CommandsByName(app.Commands))
}
func rundeamon(ctx *cli.Context) error {
   if args := ctx.Args(); args.Len() > 0 {
      return fmt.Errorf("invalid command: %q", args.Get(0))
   }
   port := ctx.Int("port")
   r := gin.Default()
   r.GET("/ping", func(c *gin.Context) {
      c.JSON(200, gin.H{
         "message": "pong",
      })
   })
   r.Run(fmt.Sprintf(":%s",strconv.Itoa(port))) // listen and serve on 0.0.0.0:8080
   return nil
}
func main()  {
   err := app.Run(os.Args)
   if err != nil {
      log.Fatal(err)
   }
}

在交互子程序上都可以些到Command 中去,在action 中去作具体操作。

 类似资料: