英文:
how to add string with quotes and slashes in golang
问题
我会分享一个例子
我想要将下面的行转换为 Golang 字符串 curl -u admin:admin -H 'Accept: application/yang-data+json' -s http://<ip>/restconf/data/ -v
我写的代码:
cmd := "curl -u admin:admin -H 'Accept: application/yang-data+json' -s http://" + ip_string + "/restconf/data/ -v"
错误:
行末尾有意外的字符串。
英文:
I'll share an example
I want the line below in golang string curl -u admin:admin -H 'Accept: application/yang-data+json' -s http://<ip>/restconf/data/ -v
code I wrote:
cmd := "curl -u admin:admin -H 'Accept: application/yang-data+json' -s http://" + ip_string + "/restconf/data/ -v"
err:
unexpected string at the end of Line.
答案1
得分: 1
> 在行尾出现了意外的字符串。
你可以使用fmt.Sprintf
来格式化字符串,这样你就不必手动拼接了。我个人认为这样更容易阅读和编写:
fmt.Sprintf("curl -u admin:admin -H 'Accept: application/yang-data+json' -s http://%s/restconf/data/ -v", ip_string)
看起来你正在尝试创建一个调用Curl的shell命令。比起尝试为shell转义你的curl
参数,直接调用curl
会更好。这样你就可以使用Go来分离参数,而不必担心shell的引用问题:
cmd := exec.Command("curl",
"-u", "admin:admin",
"-H", "Accept: application/yang-data+json",
"-s",
fmt.Sprintf("http://%s/restconf/data/", ip_string),
"-v",
)
然而,如果我是你,我会使用https://pkg.go.dev/net/http来发送请求,完全避免使用os/exec
。性能和效率会更好,处理响应和任何错误条件会比通过curl
解析输出和处理错误代码要容易得多。
req, err := http.NewRequest("GET", fmt.Sprintf("http://%s", source_ip), nil)
// 处理错误
req.Header.Add("Accept", "application/yang-data+json")
req.SetBasicAuth("admin","admin")
resp, err := client.Do(req)
// 处理错误!
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
// 处理错误!
英文:
> unexpected string at the end of Line.
You can use fmt.Sprintf
to format a string so that you don't have to stitch it together by hand. I find this easier to read and write, myself:
fmt.Sprintf("curl -u admin:admin -H 'Accept: application/yang-data+json' -s http://%s/restconf/data/ -v", ip_string)
Seems like you're trying to create a shell command to invoke Curl. Better than trying to escape your curl
arguments for the shell, is to invoke curl
directly. This way you can use Go to separate the arguments without having to worry about shell quoting:
cmd := exec.Command("curl",
"-u", "admin:admin",
"-H", "Accept: application/yang-data+json",
"-s",
fmt.Sprintf("http://%s/restconf/data/", ip_string),
"-v",
)
However, if I were you, I'd use https://pkg.go.dev/net/http to make the request and obviate os/exec
entirely. Performance and efficiency will be better, and handling the response and any error conditions will be way easier than doing that through curl
and trying to parse output and handle error codes.
req, err := http.NewRequest("GET", fmt.Sprintf("http://%s", source_ip), nil)
// handle err
req.Header.Add("Accept", "application/yang-data+json")
req.SetBasicAuth("admin","admin")
resp, err := client.Do(req)
// handle err!
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
// handle err!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论