我正在尝试使用戈兰在浏览器上打开给定的URL。当我使用此代码时,它按预期工作并在浏览器中打开给定的URL:
func main() {
url := "https://google.com"
fmt.Printf(url)
cmd := exec.Command("open", url)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
}
}
输出(打开浏览器):
~/workspace/go/so ❯ go run main.go
https://google.com%
但是当我使用 的输出作为第二个调用的参数时,程序返回如下错误:exec.Command("echo", "https://google.com")exec.Command
func main() {
output, err := exec.Command("echo", "https://google.com").Output()
if err != nil {
fmt.Println(err)
}
url := string(output)
fmt.Printf(url)
cmd := exec.Command("open", url)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err = cmd.Run()
if err != nil {
fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
}
}
输出(错误中有当前目录路径作为 URL 后面的路径):
~/workspace/go/so ❯ go run main.go
https://google.com
exit status 1: The file /Users/kadir/workspace/go/so/https:/google.com
does not exist.
我在第二个代码块中做错了什么?
我的go版本是1.17,文件是这样的:go.mod
module so
go 1.17
require github.com/urfave/cli/v2 v2.3.0
require (
github.com/cpuguy83/go-md2man/v2 v2.0.1 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect
)
心有法竹
相关分类