doty58493 2015-09-23 11:20
浏览 80
已采纳

前往:服务器开始监听后,如何启动浏览器?

In Go, how can I start the browser AFTER the server started listening ?
Preferably the simplest way possible.

My code so far, super dumbed down to the point:

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!
")
    })

    //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")
}
  • 写回答

2条回答 默认 最新

  • douzhang8144 2015-09-23 14:54
    关注

    Open the listener, start the browser and then enter the server loop:

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

    There's no need to poll as shown in another answer. The browser will connect if the listening socket is open before the browser is started.

    ListenAndServe is a convenience function that opens a socket and calls Serve. The code in this answer splits out these steps so the browser can be opened after listening starts but before the blocking call to Serve.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了