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

后端 未结 3 1462
暖寄归人
暖寄归人 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:19

    Open the listener, start the browser and then enter the server loop:

    l, err := net.Listen("tcp", "localhost:3000")
    if err != nil {
        log.Fatal(err)
    }
    
    // The browser can connect now because the listening socket is open.
    
    err := open.Start("http://localhost:3000/test")
    if err != nil {
         log.Println(err)
    }
    
    // Start the blocking server loop.
    
    log.Fatal(http.Serve(l, r)) 
    

    There's no need to poll as shown in another answer. The browser will connect if the listening socket is open before the browser is started.

    ListenAndServe is a convenience function that opens a socket and calls Serve. The code in this answer splits out these steps so the browser can be opened after listening starts but before the blocking call to Serve.

提交回复
热议问题