dougong5285 2015-07-31 04:57
浏览 267

在测试函数中运行ListenAndServe()时,端口没有关闭,该如何解决?

When I call http.ListenAndServe() in a test function the port does NOT close even after the tests have finished and the process has terminated. So the next time I run the tests I get the error "ListenAndServe: listen tcp :8080: bind: address already in use".

This does not happen when I run my program normally through main().

func TestIndex(t *testing.T) {
  handle := handlers.ServeAndHandle("8080")
  req, _ := http.NewRequest("GET", "", nil)
  w := httptest.NewRecorder()
  handle.ServeHTTP(w, req)
  if w.Code != http.StatusOK {
      t.Errorf("Home page didn't return %v", http.StatusOK)
  }
}
// this is just a wrapper function of ListenAndServe. m is of type handler
func ServeAndHandle(port string) http.Handler {
  m := &mux{}
  err := http.ListenAndServe(":"+port, m) // set listen port
  if err != nil {
      log.Fatal("ListenAndServe: ", err)
  }
  return m
}
  • 写回答

1条回答 默认 最新

  • douzhang8033 2018-05-25 12:47
    关注

    You can use NewUnstartedServer to create a instance, start it manually then defer closing it at the end of the test. Something along the lines:

    ...
    ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {  
        fmt.Fprintln(w, "Hello world")
    }))
    
    l, _ := net.Listen("tcp", URL)
    ts.Listener = l
    ts.Start()
    defer ts.Close()
    
    res, err := http.Get(URL)  
    if err != nil {
      log.Fatal(err)
    } 
    ...
    
    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序