如何在 golang 中使用标志运行函数?

问题描述

我正在制作一个 go 工具来 ping 从用户那里获取的 url,我不想遵循严格的参数顺序(例如 os.Args[] )所以我决定使用标志 {{1 }}(这是该工具想要使用的方式),但问题是我想要例如当使用“-o”标志时,我想要这个函数 output() 被执行,而不是其他函数

// 这是我的代码,我还是 Golang 的新手

./ping -u <the_url> -o <output.txt>

解决方法

在做标志时不要为字符串变量使用默认值。当您想使用 other function calls 时,只需检查您标记的变量是否为空并调用。

func main() {

    var target,out string
    flag.StringVar(&target,"t","","target to send a request")
    flag.StringVar(&out,"o","output.txt","Path to a file to store output")
    flag.Parse()

    if target != ``{
        //call your any function using target variable
        fmt.Println(target)
    }
    //call output() when you want anywhere
}

当您使用 -t flag 运行代码时,它会调用其他函数。在我的示例中,它将打印您解析的标志值。

go run main.go -t abc
abc

如果未使用 -t 标志或未对其进行值解析,则无其他函数调用。在我的示例中它不会打印任何内容。

go run main.go

您可以将它用于每个标记的变量。当您想在任何地方调用它时运行您的 output() 函数调用,因为您已为 -o 标志设置了默认值。