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

How do I run a function using flags in golang?

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

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

package main

import (
    "bufio"
    "flag"
    "fmt"
    "io/ioutil"
    "log"
    "math/rand"
    "net/http"
    "os"
    "time"
)


// this function writes output to a file

func output() {

    file, err := os.OpenFile("output.txt", os.O_WRONLY|os.O_CREATE, 0666)

    if err != nil {

        fmt.Println("File does not exists or cannot be created")

        os.Exit(1)

    }
    defer file.Close()

    w := bufio.NewWriter(file)
    r := rand.New(rand.NewSource(time.Now().UnixNano()))
    i := r.Perm(5)
    fmt.Fprintf(w, "%v\n", i)

    w.Flush()
}

// this function sends request and returns body in the response

func request_body() {

    url := <url>

    resp2, err := http.Get(url)

    if err != nil {

        log.Fatalln(err)

    } else {

        body, err := ioutil.ReadAll(resp2.Body)

        if err != nil {

            log.Fatalln(err)

        }
        res_body := string(body)

        fmt.Printf(res_body)
    }
}

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()

}

标记时不要使用字符串变量的默认值。当你想使用 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 标志设置了默认值。