doumei3828 2015-11-29 16:07
浏览 13
已采纳

在开放端口上打开URL

I'm assuming I can run a service on port 3000 like many other code samples I've seen on Github.

Now I am trying to improve my code so that it looks for an open port in case 3000 is in use:

for port := 3000; port <= 3005; port++ {
    fmt.Println(port)
    err := http.ListenAndServe(":"+strconv.Itoa(port), nil)
    if err == nil {
        fmt.Println("lk is serving", dirPath, "from http://0.0.0.0:", string(port))
        open.Start("http://0.0.0.0:" + string(port))
    }
}

However it blocks on the http.ListenAndServe line and doesn't open.Start my browser. I'm told I should use goroutines but I am still a bit bewildered how to use them in this context.

This is a "client" Web app so I do need it to invoke my browser.

  • 写回答

1条回答 默认 最新

  • doufan9377 2015-11-29 16:41
    关注

    Instead of calling ListenAndServe, create the Listener in the application and then call Serve. When creating the listener, request a free port by specifying the listener address as ":0":

    ln, err := net.Listen("tcp", ":0")
    if err != nil {
         // handle error
    }
    

    Once the listener is open, you can start the browser:

    open.Start("http://" + ln.Addr().String())
    

    and then start the server:

    if err := http.Serve(ln, nil); err != nil {
       // handle error
    }
    

    There's no need to use a goroutine.

    The code above uses addr.String() to format the listener's address. If you do need to get the port number for some reason, use a type assertion:

    if a, ok := ln.Addr().(*net.TCPAddr); ok {
       fmt.Println("port", a.Port)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)