转到:服务器开始收听后,如何启动浏览器? [英] Go: How can I start the browser AFTER the server started listening?

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

问题描述

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

最好使用最简单的方式。



我的代码如此远远超过了这一点:

  package main 

import(
/ /标准库软件包
fmt
net / http
github.com/skratchdot/open-golang/open
//第三方软件包
github.com/julienschmidt/httprouter



// go get github.com/toqueteos/webbrowser

func main(){
//实例化一个新路由器
r:= httprouter.New()

//在/ test
上添加一个处理程序r.GET(/ test, func(w http.ResponseWriter,r * http.Request,_ httprouter.Params){
//现在只需写一些测试数据
fmt.Fprint(w,Welcome!\\\

})

//open.Run(\"https://google.com/)

// open.Start(https:// google.com)

// http://127.0.0.1:3000/测试
//启动服务器
http.ListenAndServe(localhost:3000,r)
fmt.Println(ListenAndServe is blocking)
open.RunWith( http:// localhost:3000 / test,firefox)
fmt.Println(Done)
}


解决方案

如果没有错误, http.ListenAndServe() 永远不会返回。所以你不应该添加代码,除了处理失败的代码。



你必须开始一个新的goroutine,所以 ListenAndServe() code>在一个goroutine中调用,并且代码检查它是否应该在另一个goroutine上运行。



您可以检查服务器是否启动对它进行一个简单的HTTP GET 调用,例如使用 http.Get()

以下示例延迟启动7秒目的。新的goroutine为循环启动了一个无穷无尽的循环,用于检查服务器是否已启动,并在尝试之间休眠1秒。



示例:

  http.HandleFunc(/,func(w http.ResponseWriter,r * http.Request){
)w.Write([] byte(Hi!))
})

去func(){
for {
time.Sleep(time。第二个)

log.Println(检查是否开始...)
resp,err:= http.Get(http:// localhost:8081)
如果err!= nil {
log.Println(Failed:,err)
continue
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Println(Not OK:,resp.StatusCode)
continue
}

//达到了这一点:server is启动并运行!
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启动服务器... 
2015/09/23 13:53:04检查是否开始...
2015/09/23 13:53:06失败:获取http:// localhost :8081:dial tcp [:: 1]:8081:connectex:由于目标机器主动拒绝它,因此无法建立连接。
2015/09/23 13:53:07检查是否开始...
2015/09/23 13:53:09失败:获取http:// localhost:8081:dial tcp [:: 1]:8081:connectex:由于目标机器主动拒绝连接,因此无法建立连接。
2015/09/23 13:53:10检查是否开始...
2015/09/23 13:53:10服务器启动并运行!


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

解决方案

If there is no error, http.ListenAndServe() will never return. So you shouldn't add code after that except code that handles failure.

You have to start a new goroutine, so ListenAndServe() is called in one goroutine, and code checking if it is up should run on the other goroutine.

And you can check if your server is up by making a simple HTTP GET call to it, for example using http.Get().

The following example delays startup for 7 seconds on purpose. The new goroutine starts an endless for loop that checks if server is up, sleeping 1 second between attempts.

Example:

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

Example output:

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!

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

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