Home > Blockchain >  how to add string with quotes and slashes in golang
how to add string with quotes and slashes in golang

Time:11-25

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.

CodePudding user response:

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!
  •  Tags:  
  • go
  • Related