3 回答

TA貢獻1856條經驗 獲得超5個贊
打開監聽器,啟動瀏覽器,然后進入服務端循環:
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))
沒有必要進行投票,如另一個答案所示。如果在瀏覽器啟動之前打開監聽套接字,瀏覽器將連接。
ListenAndServe 是一個方便的函數,它打開一個套接字并調用 Serve。此答案中的代碼拆分了這些步驟,因此可以在偵聽開始后但在阻止調用 Serve 之前打開瀏覽器。

TA貢獻1807條經驗 獲得超9個贊
如果沒有錯誤,http.ListenAndServe()永遠不會返回。因此,除了處理失敗的代碼之外,您不應該在此之后添加代碼。
你必須啟動一個新的 goroutine,所以ListenAndServe()在一個 goroutine 中調用,檢查它是否啟動的代碼應該在另一個 goroutine 上運行。
您可以通過對其進行簡單的 HTTPGET調用來檢查您的服務器是否已啟動,例如使用http.Get().
以下示例故意將啟動延遲 7 秒。新的 goroutine 開始一個無限for循環,檢查服務器是否啟動,兩次嘗試之間休眠 1 秒。
例子:
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))
示例輸出:
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!

TA貢獻1829條經驗 獲得超6個贊
API 并不是絕對糟糕,但我們只是說“需要一些時間來適應”。以下是在 Server 結構上使用自定義屬性的方法:
s := &http.Server{
Addr: cnf.API_SERVER_ADDRESS,
Handler: h,
ReadTimeout: 0, // 1 * time.Minute,
WriteTimeout: 30 * time.Minute,
MaxHeaderBytes: 1 << 20,
}
go func() {
l, err := net.Listen("tcp", cnf.API_SERVER_ADDRESS)
if err != nil {
log.Fatal(err)
}
fmt.Println(`{"server_state":"listening"}`)
log.Fatal(s.Serve(l));
}()
因為如果你改為使用:
http.Serve(l, handler)
那么你就不能在服務器上定義自定義屬性
- 3 回答
- 0 關注
- 230 瀏覽
添加回答
舉報