服务器开始监听后如何启动浏览器? [英] How can I start the browser AFTER the server started listening?

查看:50
本文介绍了服务器开始监听后如何启动浏览器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Go中,如何在服务器开始侦听后启动浏览器?

In Go, how can I start the browser AFTER the server started listening?

最好是最简单的方法.

到目前为止,我的代码超级笨拙:

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

推荐答案

打开侦听器,启动浏览器,然后进入服务器循环:

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是一个便捷函数,它打开一个套接字并调用Serve.该答案中的代码将这些步骤分开,因此可以在侦听开始之后但在对Serve的阻止调用之前打开浏览器.

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.

这篇关于服务器开始监听后如何启动浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆