If there is no error, http.ListenAndServe() will never return. Therefore, after this, you should not add code other than code that handles the failure.
You need to start a new goroutine, so ListenAndServe() is called in one goroutine, and code checking, if it is up, should be run on another goroutine.
And you can check if your server is working by making a simple HTTP GET call for it, for example, using http.Get() .
The following example delays the launch for 7 seconds. The new goroutine launches an infinite for loop, which checks if the server is working, sleep 1 second between attempts.
Example:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hi!")) }) go func() { for { time.Sleep(time.Second) log.Println("Checking if started...") resp, err := http.Get("http://localhost:8081") if err != nil { log.Println("Failed:", err) continue } resp.Body.Close() if resp.StatusCode != http.StatusOK { log.Println("Not OK:", resp.StatusCode) continue } // Reached this point: server is up and running! break } log.Println("SERVER UP AND RUNNING!") }() log.Println("Starting server...") time.Sleep(time.Second * 7) log.Fatal(http.ListenAndServe(":8081", nil))
Output Example:
2015/09/23 13:53:03 Starting server... 2015/09/23 13:53:04 Checking if started... 2015/09/23 13:53:06 Failed: Get http://localhost:8081: dial tcp [::1]:8081: connectex: No connection could be made because the target machine actively refused it. 2015/09/23 13:53:07 Checking if started... 2015/09/23 13:53:09 Failed: Get http://localhost:8081: dial tcp [::1]:8081: connectex: No connection could be made because the target machine actively refused it. 2015/09/23 13:53:10 Checking if started... 2015/09/23 13:53:10 SERVER UP AND RUNNING!
source share