我會分享一個例子
我想要下面的 golang 字串 curl -u admin:admin -H 'Accept: application/yang-data json' -s http://<ip>/restconf/data/ -v
我寫的代碼:
指令:= "curl -u admin:admin -H 'Accept: application/yang-data json' -s http://" ip_string "/restconf/data/ -v"
錯誤:行尾出現意外字串。
uj5u.com熱心網友回復:
行尾的意外字串。
您可以使用fmt.Sprintf來格式化字串,這樣您就不必手動將其縫合在一起。我自己發現這更易于閱讀和撰寫:
fmt.Sprintf("curl -u admin:admin -H 'Accept: application/yang-data json' -s http://%s/restconf/data/ -v", ip_string)
似乎您正在嘗試創建一個 shell 命令來呼叫 Curl。比試圖為curlshell轉義你的引數更好的是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)
// 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!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/365603.html
標籤:走
下一篇:如何在Go中解鎖資料庫
