服务器开始侦听后如何启动浏览器?

在 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")

}


慕婉清6462132
浏览 194回答 3
3回答

RISEBY

打开监听器,启动浏览器,然后进入服务端循环: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.ListenAndServe()永远不会返回。因此,除了处理失败的代码之外,您不应该在此之后添加代码。你必须启动一个新的 goroutine,所以ListenAndServe()在一个 goroutine 中调用,检查它是否启动的代码应该在另一个 goroutine 上运行。您可以通过对其进行简单的 HTTPGET调用来检查您的服务器是否已启动,例如使用http.Get().以下示例故意将启动延迟 7 秒。新的 goroutine 开始一个无限for循环,检查服务器是否启动,两次尝试之间休眠 1 秒。例子:http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {    w.Write([]byte("Hi!"))})go func() {    for {        time.Sleep(time.Second)        log.Println("Checking if started...")        resp, err := http.Get("http://localhost:8081")        if err != nil {            log.Println("Failed:", err)            continue        }        resp.Body.Close()        if resp.StatusCode != http.StatusOK {            log.Println("Not OK:", resp.StatusCode)            continue        }        // Reached this point: server is up and running!        break    }    log.Println("SERVER UP AND RUNNING!")}()log.Println("Starting server...")time.Sleep(time.Second * 7)log.Fatal(http.ListenAndServe(":8081", nil))示例输出:2015/09/23 13:53:03 Starting server...2015/09/23 13:53:04 Checking if started...2015/09/23 13:53:06 Failed: Get http://localhost:8081: dial tcp [::1]:8081: connectex: No connection could be made because the target machine actively refused it.2015/09/23 13:53:07 Checking if started...2015/09/23 13:53:09 Failed: Get http://localhost:8081: dial tcp [::1]:8081: connectex: No connection could be made because the target machine actively refused it.2015/09/23 13:53:10 Checking if started...2015/09/23 13:53:10 SERVER UP AND RUNNING!

肥皂起泡泡

API 并不是绝对糟糕,但我们只是说“需要一些时间来适应”。以下是在 Server 结构上使用自定义属性的方法:s := &http.Server{&nbsp; &nbsp; Addr:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;cnf.API_SERVER_ADDRESS,&nbsp; &nbsp; Handler:&nbsp; &nbsp; &nbsp; &nbsp; h,&nbsp; &nbsp; ReadTimeout:&nbsp; &nbsp; 0, // 1 * time.Minute,&nbsp; &nbsp; WriteTimeout:&nbsp; &nbsp;30 * time.Minute,&nbsp; &nbsp; MaxHeaderBytes: 1 << 20,}go func() {&nbsp; &nbsp; l, err := net.Listen("tcp", cnf.API_SERVER_ADDRESS)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(`{"server_state":"listening"}`)&nbsp; &nbsp; log.Fatal(s.Serve(l));}()因为如果你改为使用:http.Serve(l, handler)那么你就不能在服务器上定义自定义属性
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go