英文:
How do I run a function using flags in golang?
问题
我正在制作一个Go工具,用于从用户那里获取URL并进行ping操作。我不想遵循严格的参数顺序(例如os.Args[]),所以我决定使用flags来处理这个问题,例如./ping -u <the_url> -o <output.txt>
(这是工具的使用方式),但问题是,例如当使用"-o"标志时,我希望执行output()函数,而不执行其他函数。
以下是你的代码,我是Go语言的新手:
package main
import (
"bufio"
"flag"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"time"
)
// 这个函数将输出写入文件
func output() {
file, err := os.OpenFile("output.txt", os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println("文件不存在或无法创建")
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()
}
// 这个函数发送请求并返回响应中的主体
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", "", "要发送请求的目标")
flag.StringVar(&out, "o", "output.txt", "用于存储输出的文件路径")
flag.Parse()
}
请注意,我只翻译了代码部分,不包括注释和函数中的<url>
部分。
英文:
I'm making a go tool that pings a url taken from the user, I don't want to follow a strict order of arguments ( e.g os.Args[] ) so i decided to handle this using flags ./ping -u <the_url> -o <output.txt>
(this is how the tool wanna be used ), but the problem is that i want for example when the "-o" flag is used , i want this function output() to be executed , but not the other ones ?
// Here is my code , I'm still newbie in 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()
}
答案1
得分: 1
在进行标记时,不要为字符串变量使用默认值。当你想要使用"其他函数调用"时,只需检查你的标记变量是否为空,然后进行调用。
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 != "" {
// 使用 target 变量调用任何函数
fmt.Println(target)
}
// 在任何需要的地方调用 output()
}
当你使用 -t
标记运行代码时,它将调用其他函数。在我的示例中,它将打印出你解析的标记值。
go run main.go -t abc
abc
如果未使用 -t
标记或未为其解析任何值,则不会调用其他函数。在我的示例中,它将不会打印任何内容。
go run main.go
你可以对每个标记变量都使用这种方法。并且由于你已经为 -o
标记设置了默认值,所以可以在任何需要的地方运行 output()
函数调用。
英文:
Don't use default value for the string variable when you do flag. And when you want to use other function calls
, just check that your flagged variables are empty or not and call.
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
}
when you run code with -t flag
, it will call the other functions. In my example it will print your parsed flag value.
go run main.go -t abc
abc
if -t flag not used or not value parse for it, No other function calls. It will print nothin in my example.
go run main.go
You can use this for every flagged variable. And run your output()
function call when you want to call it anywhere because you have set default value for -o
flag.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论