我不确定这将如何工作,但我基本上是在尝试编写一个命令行应用程序,我可以从中运行命令和子命令。我正在使用这个流行的第三方库来解析命令行参数:
我的问题是我有一个项目文件夹,我的 .go 文件将存放在该文件夹中:
MyProject
所以即使在我的 main.go 文件中的代码中,使用他们的示例,我也有:
package main
import (
"fmt"
"os"
"github.com/urfave/cli"
)
func main() {
app := cli.NewApp()
app.Name = "greet"
app.Usage = "fight the loneliness!"
app.Action = func(c *cli.Context) error {
fmt.Println("Hello friend!")
return nil
}
app.Run(os.Args)
}
当我运行 go install
时,
在我的 $GOPATH/bin 目录中,我实际上构建了 MyProject。然后当我从终端运行 MyProject
时,我得到了
USAGE:
myproject [global options] command [command options] [arguments...]
但实际上,我不需要先执行 myproject
命令。有没有一种方法通常使用命令行应用程序或第三方包来创建命令行应用程序,这样我就可以从命令行运行 greet
而不是 myproject
作为第一个命令?
最佳答案
查看 go build command 的文档
go build [-o output] [-i] [build flags] [packages]
When compiling a single main package, build writes the resulting executable to an output file named after the first source file ('go build ed.go rx.go' writes 'ed' or 'ed.exe') or the source code directory ('go build unix/sam' writes 'sam' or 'sam.exe'). The '.exe' suffix is added when writing a Windows executable.
When compiling multiple packages or a single non-main package, build compiles the packages but discards the resulting object, serving only as a check that the packages can be built.
The -o flag, only allowed when compiling a single package, forces build to write the resulting executable or object to the named output file, instead of the default behavior described in the last two paragraphs.
尝试像这样构建它 go build -o greet
如果您希望从任何地方都可以访问它,请不要忘记将生成的可执行文件添加到您的 $PATH
中。
或者,您可以 1) 创建一个别名;或 2) 指向实际可执行文件的符号链接(symbolic link):
alias greet='myproject'
ln -s $GOPATH/bin/myproject greet
(链接将在当前目录中创建)
关于go - 使用 GoLang 命令行应用程序安装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37691028/