github.com/nalind/docker@v1.5.0/pkg/listenbuffer/buffer.go (about) 1 /* 2 Package to allow go applications to immediately start 3 listening on a socket, unix, tcp, udp but hold connections 4 until the application has booted and is ready to accept them 5 */ 6 package listenbuffer 7 8 import "net" 9 10 // NewListenBuffer returns a listener listening on addr with the protocol. 11 func NewListenBuffer(proto, addr string, activate chan struct{}) (net.Listener, error) { 12 wrapped, err := net.Listen(proto, addr) 13 if err != nil { 14 return nil, err 15 } 16 17 return &defaultListener{ 18 wrapped: wrapped, 19 activate: activate, 20 }, nil 21 } 22 23 type defaultListener struct { 24 wrapped net.Listener // the real listener to wrap 25 ready bool // is the listner ready to start accpeting connections 26 activate chan struct{} 27 } 28 29 func (l *defaultListener) Close() error { 30 return l.wrapped.Close() 31 } 32 33 func (l *defaultListener) Addr() net.Addr { 34 return l.wrapped.Addr() 35 } 36 37 func (l *defaultListener) Accept() (net.Conn, error) { 38 // if the listen has been told it is ready then we can go ahead and 39 // start returning connections 40 if l.ready { 41 return l.wrapped.Accept() 42 } 43 <-l.activate 44 l.ready = true 45 return l.Accept() 46 }