Go: How can I start the browser AFTER the server started listening?

后端 未结 3 1454
暖寄归人
暖寄归人 2020-12-15 07:40

In Go, how can I start the browser AFTER the server started listening ?
Preferably the simplest way possible.

My code so far, super dumbed down to the point:<

3条回答
  •  时光取名叫无心
    2020-12-15 08:07

    If there is no error, http.ListenAndServe() will never return. So you shouldn't add code after that except code that handles failure.

    You have to start a new goroutine, so ListenAndServe() is called in one goroutine, and code checking if it is up should run on the other goroutine.

    And you can check if your server is up by making a simple HTTP GET call to it, for example using http.Get().

    The following example delays startup for 7 seconds on purpose. The new goroutine starts an endless for loop that checks if server is up, sleeping 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))
    

    Example output:

    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!
    

提交回复
热议问题