在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")
}
http.ListenAndServe
改为 "非阻塞式" 并不是很复杂:只需使用go http.ListenAndServe(...)
,加上适当的错误处理即可。那么问题究竟在哪里呢? - Volkerhttp.ListenAndServe()
,然后休眠一段时间(例如200毫秒),最后在浏览器中打开即可。 - Eric