如何确定Go http ListenAndServe选择的临时端口

时间:2018-10-23 08:39:18

标签: http go tcp

使用http.ListenAndServe(),我可以在Go中启动Web服务器。当addr string:0时,将按预期让操作系统选择一个临时端口。当我运行netstat -nptl时,该端口显示就很好。

由于http.ListenAndServe()在成功的情况下不会返回,因此仅在出现错误时才返回,据我所知我无法使用它。

所以我尝试了以下方法:

package main

import (
    "net/http"
    "fmt"
    "time"
)

//noinspection GoUnusedParameter
func hello(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello, world!\n"))
}

func main() {
    http.HandleFunc("/", hello)
    sync := make(chan string)
    server := &http.Server{Addr: ":0", Handler: nil}
    go func() {
        if err := server.ListenAndServe(); err != nil {
            sync <- "done"
            panic(err)
        }
    }()
    time.Sleep(2 * time.Second)
    fmt.Printf("Listening to: %s\n", server.Addr)
    msg := <- sync
    fmt.Println(msg)
}

但是,这将显示“:0”,而不是服务器正在运行的实际端口。

我如何在Go本身中(例如,通过其httpserver API)以编程方式确定服务器在哪个实际端口上运行,这在使其临时运行时非常有用港口?同样,最好是不需要像我这样丑陋的Sleep通话。

(在有人问之前:我希望该软件能够在临时端口上运行,以免端口冲突。而且,在临时端口上运行可以避免测试中的竞争条件,但显然要求我可以确定端口。)

0 个答案:

没有答案
相关问题