在 Go 中,如何在服务器开始监听后启动浏览器?
最好是最简单的方法。
到目前为止,我的代码非常简单:
package main
import (
// Standard library packages
"fmt"
"net/http"
"github.com/skratchdot/open-golang/open"
// Third party packages
"github.com/julienschmidt/httprouter"
)
// go get github.com/toqueteos/webbrowser
func main() {
// Instantiate a new router
r := httprouter.New()
// Add a handler on /test
r.GET("/test", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
// Simply write some test data for now
fmt.Fprint(w, "Welcome!\n")
})
//open.Run("https://google.com/")
// open.Start("https://google.com")
// http://127.0.0.1:3000/test
// Fire up the server
http.ListenAndServe("localhost:3000", r)
fmt.Println("ListenAndServe is blocking")
open.RunWith("http://localhost:3000/test", "firefox")
fmt.Println("Done")
}
最佳答案
打开监听器,启动浏览器然后进入服务器循环:
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))
不需要像另一个答案中那样进行投票。如果监听套接字在浏览器启动前打开,浏览器将连接。
ListenAndServe 是一个方便的函数,它打开一个套接字并调用 Serve。此答案中的代码拆分了这些步骤,以便可以在监听开始后但在对 Serve 的阻塞调用之前打开浏览器。
关于http - 服务器开始监听后如何启动浏览器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32738188/