zoukankan      html  css  js  c++  java
  • cli框架 获取 命令行 参数

    package main

    import (
    "fmt"
    "log"
    "os"

    "github.com/urfave/cli"
    )

    func main() {
    //实例化一个命令行程序
    oApp := cli.NewApp()
    //程序名称
    oApp.Name = "GoTool"
    //程序的用途描述
    oApp.Usage = "To save the world"
    //程序的版本号
    oApp.Version = "1.0.0"

    //预置变量
    var host string
    var debug bool

    //设置启动参数
    oApp.Flags = []cli.Flag{
    //参数string, int, bool
    &cli.StringFlag{
    Name: "host", //参数名称
    Value: "127.0.0.1", //参数默认值
    Usage: "Server Address", //参数功能描述
    Destination: &host, //接收值的变量
    },
    &cli.IntFlag{
    Name: "port, p",
    Value: 8888,
    Usage: "Server port",
    },
    &cli.BoolFlag{
    Name: "debug",
    Usage: "debug mode",
    Destination: &debug,
    },
    }
    //该程序执行的代码
    oApp.Action = func(c *cli.Context) error {
    fmt.Println("Test")
    fmt.Printf("host=%v ", host)
    fmt.Printf("port=%v ", c.Int("port")) //不使用变量接收,直接解析
    fmt.Printf("debug=%v ", debug)
    return nil
    }

    //设置多个命令,不同的命令执行不同的操作
    //oApp.Commands = []cli.Command{
    // {
    // //命令全称
    // Name: "lang",
    // //命令简写
    // Aliases: []string{"l"},
    // //命令详细描述
    // Usage: "Setting language",
    // //命令处理函数
    // Action: func(c *cli.Context) {
    // //通过c.Args().First()获取命令行参数
    // fmt.Printf("language=%v ", c.Args().First())
    // },
    // },
    // {
    // Name: "encode",
    // Aliases: []string{"e"},
    // Usage: "Setting encoding",
    // Action: func(c *cli.Context) {
    // fmt.Printf("encoding=%v ", c.Args().First())
    // },
    // },
    //}

    if err := oApp.Run(os.Args); err != nil {
    log.Fatal(err)
    }

    }


    ➜ test go run testNew.go --port 777 --host=8.0.0.0 --debug=true
    Test
    host=8.0.0.0
    port=777
    debug=true

  • 相关阅读:
    vm12序列号
    三星手机官方固件下载
    MSTP故障处理手册
    分享一个高清壁纸网站
    ThinkPad X220 完美黑苹果 Hackintosh OS X 10.11 El Capitan
    一句命令激活windows/office
    Win10+VMplayer12中U盘无法挂载解决
    记一次金士顿DT100 G3 32G修复
    飘雪代码2枚
    禁用安全模式
  • 原文地址:https://www.cnblogs.com/lgj8/p/12089963.html
Copyright © 2011-2022 走看看