在 Go 中,服务器开始监听后打开浏览器可以通过稍微修改的方法来实现。操作方法如下:
package main import ( "fmt" "log" "net" "net/http" "github.com/julienschmidt/httprouter" "github.com/skratchdot/open-golang/open" ) // Add a handler on "/test" func main() { // Instantiate a new router r := httprouter.New() 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 the listener l, err := net.Listen("tcp", ":3000") if err != nil { log.Fatal(err) } // Start the browser err = open.Run("http://localhost:3000/test") if err != nil { log.Fatal(err) } // Enter the server loop if err := http.Serve(l, r); err != http.ErrServerClosed { log.Fatal(err) } }
代码遵循以下流程:
以上是如何在启动Go HTTP服务器后自动打开浏览器?的详细内容。更多信息请关注PHP中文网其他相关文章!