Skip to content

Commit

Permalink
net/http/httptest: fix race in Close()
Browse files Browse the repository at this point in the history
Fixes golang#51799

Signed-off-by: Maisem Ali <[email protected]>
  • Loading branch information
Maisem Ali committed Mar 18, 2022
1 parent cc2e7f3 commit deb434e
Showing 1 changed file with 6 additions and 17 deletions.
23 changes: 6 additions & 17 deletions src/net/http/httptest/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -317,12 +317,6 @@ func (s *Server) wrap() {
s.mu.Lock()
defer s.mu.Unlock()

// Keep Close from returning until the user's ConnState hook
// (if any) finishes. Without this, the call to forgetConn
// below might send the count to 0 before we run the hook.
s.wg.Add(1)
defer s.wg.Done()

switch cs {
case http.StateNew:
s.wg.Add(1)
Expand Down Expand Up @@ -358,7 +352,12 @@ func (s *Server) wrap() {
s.closeConn(c)
}
case http.StateHijacked, http.StateClosed:
s.forgetConn(c)
if _, ok := s.conns[c]; ok {
delete(s.conns, c)
// Keep Close from returning until the user's ConnState hook
// (if any) finishes.
defer s.wg.Done()
}
}
if oldHook != nil {
oldHook(c, cs)
Expand All @@ -378,13 +377,3 @@ func (s *Server) closeConnChan(c net.Conn, done chan<- struct{}) {
done <- struct{}{}
}
}

// forgetConn removes c from the set of tracked conns and decrements it from the
// waitgroup, unless it was previously removed.
// s.mu must be held.
func (s *Server) forgetConn(c net.Conn) {
if _, ok := s.conns[c]; ok {
delete(s.conns, c)
s.wg.Done()
}
}

0 comments on commit deb434e

Please sign in to comment.