在 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中文網其他相關文章!