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
}