File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -3,11 +3,13 @@ package server
33import (
44 "net"
55 "strconv"
6+ "sync"
67)
78
89type Server struct {
910 listeners []* Listener
1011 closeChannel chan int
12+ stopOnce sync.Once
1113}
1214
1315type ConnectionType string
@@ -32,12 +34,14 @@ func NewServer(listeners []*Listener) *Server {
3234 return & Server {
3335 listeners : listeners ,
3436 closeChannel : make (chan int ),
37+ stopOnce : sync.Once {},
3538 }
3639}
3740
3841func (s * Server ) Stop () {
39- s .closeChannel <- 0
40- close (s .closeChannel )
42+ s .stopOnce .Do (func () {
43+ close (s .closeChannel )
44+ })
4145}
4246
4347func (s * Server ) Start () {
Original file line number Diff line number Diff line change 1+ package server
2+
3+ import "testing"
4+
5+ func TestServerStopIdempotent (t * testing.T ) {
6+ s := NewServer ([]* Listener {})
7+ // call Stop multiple times; should not panic
8+ s .Stop ()
9+ defer func () {
10+ if r := recover (); r != nil {
11+ t .Fatalf ("Stop panicked on second call: %v" , r )
12+ }
13+ }()
14+ s .Stop ()
15+ }
You can’t perform that action at this time.
0 commit comments