sho*_*a T -1 shell command-line-interface go go-cobra
我使用以下代码创建应根据cli传递的一些标志运行的命令。
我使用眼镜蛇回购 https://github.com/spf13/cobra
当我运行它 go run main.go echo test
我懂了
Print: test
哪个有效。
现在,我运行go install打开bin目录,然后单击文件newApp(这是我的应用程序的名称)
它打印
Usage:
MZR [command]
Available Commands:
echo Echo anything to the screen
help Help about any command
print Print anything to the screen
Flags:
-h, --help help for MZR
Use "MZR [command] --help" for more information about a command.
[Process completed]
Run Code Online (Sandbox Code Playgroud)
而且我不使用MZR echo在本地运行时可以使用的任何命令(例如)go run main.go echo test
但是我想像 下面 那样使用它,MZR -h 或者MZR echo,我该怎么做?(并将我在go install- 之后创建的bin中的文件也提供给我的朋友Unix executable - 3.8 MB)
例如,像这个仓库一样,它使用相同的命令行工具并运行它,您可以使用hoarder --server
https://github.com/nanopack/hoarder
例如,这是代码(使其更简单)
package main
import (
"fmt"
"strings"
"github.com/spf13/cobra"
)
func main() {
var echoTimes int
var cmdPrint = &cobra.Command{
Use: "print [string to print]",
Short: "Print anything to the screen",
Long: `print is for printing anything back to the screen.
For many years people have printed back to the screen.`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Print: " + strings.Join(args, " "))
},
}
var cmdEcho = &cobra.Command{
Use: "echo [string to echo]",
Short: "Echo anything to the screen",
Long: `echo is for echoing anything back.
Echo works a lot like print, except it has a child command.`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Print: " + strings.Join(args, " "))
},
}
var cmdTimes = &cobra.Command{
Use: "times [# times] [string to echo]",
Short: "Echo anything to the screen more times",
Long: `echo things multiple times back to the user by providing
a count and a string.`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
for i := 0; i < echoTimes; i++ {
fmt.Println("Echo: " + strings.Join(args, " "))
}
},
}
cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
var rootCmd = &cobra.Command{Use: "MZR"}
rootCmd.AddCommand(cmdPrint, cmdEcho)
cmdEcho.AddCommand(cmdTimes)
rootCmd.Execute()
}
Run Code Online (Sandbox Code Playgroud)
可执行文件的名称取自目录名称。将目录重命名newApp为MZR。进行此更改后,该go install命令将创建一个名为的可执行文件MZR。如果可执行文件在您的路径上,则可以使用MZR -h或从命令行运行它MZR echo。
| 归档时间: |
|
| 查看次数: |
154 次 |
| 最近记录: |