Documentation
¶
Overview ¶
Package listener provides utility for allocating a net.Listener from address candidates.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Listener ¶
type Listener struct {
// URL to the listener.
// This is always "http://localhost:PORT" regardless of the listening address.
URL *url.URL
// contains filtered or unexported fields
}
Listener wraps a net.Listener and provides its URL.
func New ¶
New starts a Listener on one of the addresses. Caller should close the listener finally.
If nil or an empty slice is given, it defaults to "127.0.0.1:0". If multiple address are given, it will try the addresses in order.
If the port in the address is 0, it will allocate a free port.
If no port is available, it will return an error which wraps NoAvailablePortError.
Example ¶
ExampleNew allocates a net.Listener at port 18000 or 28000.
package main
import (
"fmt"
"github.com/int128/listener"
)
func main() {
l, err := listener.New([]string{"127.0.0.1:18000", "127.0.0.1:28000"})
if err != nil {
panic(err)
}
defer func() {
if err := l.Close(); err != nil {
panic(err)
}
}()
fmt.Printf("Open %s", l.URL)
}
Output: Open http://localhost:18000
type NoAvailablePortError ¶ added in v1.1.0
type NoAvailablePortError interface {
Unwrap() []error
}
NoAvailablePortError contains the causes of port allocation failure.