【发布时间】:2015-12-20 16:32:47
【问题描述】:
在 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")
}
【问题讨论】:
-
在 Go 中,“阻塞”
http.ListenAndServe“非阻塞”:go http.ListenAndServe(...)并不是很复杂,可能需要一些错误处理。那么究竟是什么问题呢? -
@Volker:问题是,这是我的第一步,所以我还不是很流利,否则我只会创建一个新线程并休眠几毫秒在打开浏览器之前;目前我还有其他事情要做;)另外,如果 ListenAndServer 是非阻塞的,它会在主程序退出的那一刻退出(AFAIK),这将是立即的。
-
只需在单独的 go 例程中运行
http.ListenAndServe(),然后休眠一段时间(例如 200 毫秒),然后在浏览器中打开。