Golang Error - Undeclared name: xxx compiler [closed] - go

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am writing a snippet of Golang to perform a curl command that was correctly written in bash script. Here is what I have so far (in VSCode):
url="https://<DOMAIN>/blah/blah/blah/" //<--valid url, used in bash script and it worked
cmd := exec.Command("curl", "-s --user <USERNAME> --request GET --url "+url+" --header 'Accept: application/json'")
out, err = cmd.Output()
if err != nil {
fmt.Println("erorr", err)
return false
}
fmt.Println(out)
All of that ends up giving me the errors "undeclared name: err (compile)" and "undeclared name: out (compile)" on the different lines where I use out and err. I saw this format used on a post here so that's where I got this from. I can't figure out the right way to use Stdin or Stdout in this situation. Can anybody help?

Your compiler errors are due to this line, which tries to assign to two variables that (as the error says) are undeclared:
out, err = cmd.Output()
This should probably be a short variable declaration, i.e.:
out, err := cmd.Output()
However, once that's fixed, it still won't work, because you're passing all of your CLI params to curl as a single argument. It should be:
cmd := exec.Command("curl", "-s", "--user", "<USERNAME>", "--request", "GET", "--url", url, "--header", "Accept: application/json")
Though it's fairly unusual to invoke curl from a Go program; typically you'd use the HTTP client that already exists in net/http, so it's likely that all of this code should be replaced with use of the native client.

In your code you have missed the colon ,use := instead of =
url="https://<DOMAIN>/blah/blah/blah/" //<--valid url, used in bash script and it worked
cmd := exec.Command("curl", "-s --user <USERNAME> --request GET --url "+url+" --header 'Accept: application/json'")
out, err := cmd.Output()
if err != nil {
fmt.Println("erorr", err)
return false
}
fmt.Println(out)

Related

Reading a process name how it is displayed in Windows Task Manager in Golang

I'm currently trying to read the name of a process in Go how it is represented in the windows task manager.
However, when I read it in Go it is displayed always as the executable. I'm trying to get it how it is named in the task manager.
Code:
package main
import (
"fmt"
"github.com/shirou/gopsutil/process"
)
func main() {
p, _ := process.Processes()
for _, pr := range p {
fmt.Println(pr.Name())
}
}
This outputs all process names but none match how it is shown here:
I am trying to read the Spotify process name that is displayed with the song title.
Get window title
Each time you open the "Windows Task Manager" it searches for .Net process.MainWindowTitle property, so you cant grep Windows title using gopsutil ... you have to use some Go wrapper for the .NET Core Runtime , not sure maybe this one would be helpful ... or even use C# instead of Golang
Get currently playing track on Spotify
Spotify has awesome docs with API usage for such case
so you only need to generate auth token and convert next curl request to golang fetch function
curl -X "GET" "https://api.spotify.com/v1/me/player/currently-playing?market=UA" -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer <<YOUR TOKEN>>"

How can I get HTTP RPC Server and client to work?

I am trying to send messages from client to server and back using the exact HTTP RPC server/client code given here.
However, when I run the server, my command line becomes blank because the server starts listening using:
err := http.ListenAndServe(":1234", nil)
if err != nil {
fmt.Println(err.Error())
}
In the client code, I need to get an argument from the command line for client to run:
serverAddress := os.Args[1]
However, this argument is not available because the server code makes my command line blank.
How can I get the server and client to work on the same command line window?

golang exec incorrect behavior

I'm using following code segment to get the XML definition of a virtual machine running on XEN Hypervisor. The code is trying to execute the command virsh dumpxml Ubutnu14 which will give the XML of the VM named Ubuntu14
virshCmd := exec.Command("virsh", "dumpxml", "Ubuntu14")
var virshCmdOutput bytes.Buffer
var stderr bytes.Buffer
virshCmd.Stdout = &virshCmdOutput
virshCmd.Stderr = &stderr
err := virshCmd.Run()
if err != nil {
fmt.Println(err)
fmt.Println(stderr.String())
}
fmt.Println(virshCmdOutput.String())
This code always goes into the error condition for the given domain name and I get the following output.
exit status 1
error: failed to get domain 'Ubuntu14'
error: Domain not found: no domain with matching name 'Ubuntu14'
But if I run the standalone command virsh dumpxml Ubuntu14, I get the correct XML definition.
I would appreciate if someone could give me some hints on what I'm doing wrong. My host machine is Ubuntu-16.04 and golang version is go1.6.2 linux/amd64
I expect you are running virsh as a different user in these two scenarios, and since you don't provide any URI, it is connecting to a different libvirtd instance. If you run virsh as non-root, then it'll usually connect to qemu:///session, but if you run virsh as root, then it'll usually connect to qemu:///system. VMs registered against one URI, will not be visible when connecting to the other URI.
BTW, if you're using go, you'd be much better off using the native Go library bindings for libvirt instead of exec'ing virsh. Your "virsh dumpxml" invokation is pretty much equivalent to this:
import (
"github.com/libvirt/libvirt-go"
)
conn, err := libvirt.NewConnect("qemu:///system")
dom, err := conn.LookupDomainByName("Ubuntu14")
xml, err := dom.GetXMLDesc(0)
(obviously do error handling too)

exec.Command does not register error from Go's own pprof tool

Here is my code:
cmd := exec.Command("go", "tool", "pprof", "-dot", "-lines", "http://google.com")
out, err := cmd.Output()
if err != nil {
panic(err)
}
println(string(out))
When I run the exact same command in my console, I see:
$ go tool pprof -dot -lines http://google.com
Fetching profile from http://google.com/profilez
Please wait... (30s)
server response: 404 Not Found
However, my go program does not register that this is an error. Oddly, the variable out prints as an empty string and err is nil. What is going on?
To clarify, I am profiling http://google.com to purposefully create an error. I would normally profile a real Go application.
The text
Fetching profile from http://google.com/profilez
Please wait... (30s)
server response: 404 Not Found
is written to stderr. Your program captures stdout, which is empty. Consider calling:
out, err := cmd.CombinedOutput()
to grab both stdout and stderr.
cmd.Output() and cmd.CombinedOutput() return err == nil because the command exits with status zero. Perhaps an issue should be filed requesting that the command exit with non-zero status.

print params each in curl [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i need to increment the userb and usere but when i write my variable in curl , and when i try it i get nothing
(1..180000).step(20000)do |userb|
(20000..180000).step(20000)do |usere|
curl = %x[ curl -i -s -H "Host: xxxx" "http://XXXXX/scripts/exportStatsCsv/testA1?start='+ userb +'&end='+ usere +'&startDate='#{#array_timestampdate[0]}'&endDate='#{#array_timestampdate[1]}'" ] sleep(10)
end
end
Try running your code with warnings and debugging turned on:
ruby -cW2 path/to/your/code
You should see something like:
syntax error, unexpected tIDENTIFIER, expecting keyword_end
... sleep(10)
... ^
You need to do this as a first step when you run into a problem. Ruby will give you more detailed information about problems with the script when warnings are enabled and set to their highest value. Here's what the flags mean:
-c check syntax only
-W[level=2] set warning level; 0=silence, 1=medium, 2=verbose
You're getting this error, because sleep(10) needs to be executed as a separate statement. You can either insert ; between it, and the call to cURL, or put it on its one line. I'd recommend the second option in order to make the commands easier to read.
Also, I'd highly recommend using the Curb gem instead of launching cURL in a sub-shell like you are. You're losing flexibility and wasting CPU time having Ruby, then the OS, create a new shell to launch cURL.
Finally, you need to learn to write your code more clearly or you'll paint yourself into corners of confusion in no time. Here's a starting point for how I'd write the code:
require 'uri'
#array_timestampdate = ['start_date', 'end_date']
(1..180000).step(20000) do |userb|
(20000..180000).step(20000) do |usere|
uri = URI.parse('http://XXXXX/scripts/exportStatsCsv/testA1')
uri.query = URI.encode_www_form(
{
'start' => userb,
'end' => usere,
'startDate' => #array_timestampdate[0],
'endDate' => #array_timestampdate[1]
}
)
curl = %Q[ curl -i -s -H "Host: xxxx" "#{uri.to_s}" ]
puts curl
end
end
With a little example of the output:
>> curl -i -s -H "Host: xxxx" "http://XXXXX/scripts/exportStatsCsv/testA1?start=1&end=20000&startDate=start_date&endDate=end_date"
...
>> curl -i -s -H "Host: xxxx" "http://XXXXX/scripts/exportStatsCsv/testA1?start=160001&end=180000&startDate=start_date&endDate=end_date"

Resources