github.com/haraldrudell/parl@v0.4.176/pnet/listener.go (about) 1 /* 2 © 2023–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package pnet 7 8 import ( 9 "context" 10 "net" 11 "sync/atomic" 12 13 "github.com/haraldrudell/parl/perrors" 14 ) 15 16 // Listen obtains a tcp or other listener 17 // - network must be set. 18 // NetworkDefault yields “panic: listen: unknown network” 19 // - addr can be empty 20 // - default port is ephemeral, a high number like 59321 21 // - if IPv6 is allowed, default host typically becomes “::” not “::1” 22 // - limited to IPv4, eg. NetworkTCP4, default host typically becomes “0.0.0.0” not “127.0.0.1” 23 func Listen( 24 network Network, addr string, 25 cancel *atomic.Pointer[context.CancelFunc], 26 ) (listener net.Listener, err error) { 27 var ctx, cancelFunc = context.WithCancel(context.Background()) 28 defer cancelFunc() 29 cancel.Store(&cancelFunc) 30 defer cancel.Store(nil) 31 32 var listenConfig = net.ListenConfig{} 33 listener, err = listenConfig.Listen(ctx, network.String(), addr) 34 if err != nil { 35 err = perrors.ErrorfPF("net.Listen %s %s: '%w'", network, addr, err) 36 } 37 38 return 39 }