I don't understand why my code has syntax error.
package main
import (
"fmt"
"os/exec"
"time"
)
func ping(curl_out string) endtime int64 {
try_curl := exec.Command("curl", "localhost:8500/v1/catalog/nodes")
try_curl_out := try_curl.Output()
for try_curl_out == curl_out {
try_curl := exec.Command("curl", "localhost:8500/v1/catalog/nodes")
try_curl_out := try_curl.Output()
}
endtime := time.Now().Unix()
return endtime
}
func main() {
run_container := exec.Command("docker", "run", "-p", "8400:8400", "-p", "8500:8500", "-p", "8600:53/udp", "-h", "node1", "progrium/consul", "-server", "-bootstrap")
container_id, err := run_container.Output()
if err != nil {
fmt.Println(err)
return
}
run_curl := exec.Command("curl", "localhost:8500/v1/catalog/nodes")
curl_out, err := run_curl.Output()
if err != nil {
fmt.Println(err)
return
}
endtime := go ping(string(curl_out))
container_id, err = exec.Command("docker", "stop", container_id)
if err != nil {
fmt.Println(err)
return
}
startime := time.Now().Unix()
fmt.Println("delay is", endtime-startime)
}
# command-line-arguments
./main.go:9: syntax error: unexpected name, expecting semicolon or newline
./main.go:11: non-declaration statement outside function body
./main.go:15: non-declaration statement outside function body
./main.go:16: non-declaration statement outside function body
./main.go:17: non-declaration statement outside function body
./main.go:18: syntax error: unexpected }
This code calculates time between docker start and stop. I use routine to return end time.
endtime := go ping(string(curl_out))
I think it's wrong. How can I use keyword go?
In Go, Do I decelerate statement outside function body?
There's 2 primary issues (and many unrelated).
First, you need to parenthesize named return parameters
func ping(curl_out string) (endtime int64) {
Second, you can't assign the return value of a goroutine. It's executed asynchronously in an entirely new context. Use a channel to communicate between goroutines
You could declare the ping function like:
func ping(curl_out string, endtime chan<- int64) {
And then pass in a channel on which to receive the value
ch := make(chan int64)
go ping(string(curl_out), ch)
endtime <- ch
(Though there is no point in this case to using a goroutine, since you want the value synchronously)
In line 9:
Add parenthesis
func ping(curl_out string) (endtime int64) {
or remove return value name:
func ping(curl_out string) int64 {
And you're right about the use of go
keyword to create a goroutine, you can't assign that to a return value, just remove the go
keyword and assign the value directly.
Also (style) go variables are in camelCase so you should change your variables from run_container
to either runContainer
or better just container
or even better just c
, same goes for run_curl
it could be curl
Here's an slightly enhanced version of your code ( without really knowing what it does)