| 9 |
| 10 | // baseGroup contains the shared plumbing for listener-based groups |
| 11 | // (TCP, HTTPS, TCPMux). Each concrete group embeds this and provides |
| 12 | // its own Listen method with protocol-specific validation. |
| 13 | type baseGroup struct { |
| 14 | group string |
| 15 | groupKey string |
| 16 |
| 17 | acceptCh chan net.Conn |
| 18 | realLn net.Listener |
| 19 | lns []*Listener |
| 20 | mu sync.Mutex |
| 21 | cleanupFn func() |
| 22 | } |
| 23 |
| 24 | // initBase resets the baseGroup for a fresh listen cycle. |
| 25 | // Must be called under mu when len(lns) == 0. |
| 26 | func (bg *baseGroup) initBase(group, groupKey string, realLn net.Listener, cleanupFn func()) { |
| 27 | bg.group = group |
| 28 | bg.groupKey = groupKey |
| 29 | bg.realLn = realLn |
| 30 | bg.acceptCh = make(chan net.Conn) |
| 31 | bg.cleanupFn = cleanupFn |
| 32 | } |
| 33 |
| 34 | // worker reads from the real listener and fans out to acceptCh. |
| 35 | // The parameters are captured at creation time so that the worker is |
| 36 | // bound to a specific listen cycle and cannot observe a later initBase. |
| 37 | func (bg *baseGroup) worker(realLn net.Listener, acceptCh chan<- net.Conn) { |
| 38 | for { |
| 39 | c, err := realLn.Accept() |
| 40 | if err != nil { |
| 41 | return |
| 42 | } |
| 43 | err = gerr.PanicToError(func() { |
| 44 | acceptCh <- c |
| 45 | }) |
| 46 | if err != nil { |
| 47 | c.Close() |
| 48 | return |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 |
| 53 | // newListener creates a new Listener wired to this baseGroup. |
| 54 | // Must be called under mu. |
| 55 | func (bg *baseGroup) newListener(addr net.Addr) *Listener { |
| 56 | ln := newListener(bg.acceptCh, addr, bg.closeListener) |
| 57 | bg.lns = append(bg.lns, ln) |
| 58 | return ln |
| 59 | } |
| 60 |
| 61 | // closeListener removes ln from the list. When the last listener is removed, |
| 62 | // it closes acceptCh, closes the real listener, and calls cleanupFn. |
| 63 | func (bg *baseGroup) closeListener(ln *Listener) { |
| 64 | bg.mu.Lock() |
| 65 | defer bg.mu.Unlock() |
| 66 | for i, l := range bg.lns { |
| 67 | if l == ln { |
| 68 | bg.lns = append(bg.lns[:i], bg.lns[i+1:]...) |
| 69 | break |
| 70 | } |
| 71 | } |
| 72 | if len(bg.lns) == 0 { |
| 73 | close(bg.acceptCh) |
| 74 | bg.realLn.Close() |
| 75 | bg.cleanupFn() |
| 76 | } |
| 77 | } |