Probe TCP Readiness With DialTimeout
Check service readiness with net.DialTimeout: dial with a bounded budget, close the descriptor immediately, and treat refusal and timeout as distinct outcomes.
Code
package main
import (
"fmt"
"net"
"time"
)
// probe attempts a TCP connection within a budget;
// refusal and timeout are two different failure kinds, both returned from here
func probe(addr string, budget time.Duration) error {
conn, err := net.DialTimeout("tcp", addr, budget)
if err != nil {
return err
}
return conn.Close() // release the descriptor as soon as the probe is done
}
func main() {
// a real local listener with a system-assigned port keeps the example reproducible
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
fmt.Println("listen:", err)
return
}
defer ln.Close()
up := ln.Addr().String()
if err := probe(up, time.Second); err != nil {
fmt.Println("readiness check failed:", err)
} else {
fmt.Println("readiness ok:", up)
}
// occupy a port and close it again: it is free right now, so the connection must be refused
tmp, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
fmt.Println("listen:", err)
return
}
closedAddr := tmp.Addr().String()
tmp.Close()
if err := probe(closedAddr, 200*time.Millisecond); err != nil {
fmt.Println("not ready:", closedAddr)
}
}How the snippet works
Probe TCP Readiness With DialTimeout reduces to the functions probe and main.
Failures are values here: 5 sites check err and decide instead of letting one propagate. The cleanup call is deferred to function exit — success, early return, and panic all covered.
Caveats
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Using it
Signature: func probe(addr string, budget time.Duration) error
Running the file prints labeled results such as listen:, readiness check failed:, readiness ok: — each operation’s effect is visible in the output.
The sequence probe lives in main; running the file triggers it.
Key statements
func probe(addr string, budget time.Duration) error {
conn, err := net.DialTimeout("tcp", addr, budget)
if err != nil {
return err
}
return conn.Close() // release the descriptor as soon as the probe is done
}
if err != nil {
fmt.Println("listen:", err)
return
}
defer ln.Close()
Interactive Tools for This Topic
FAQ
- How should callers handle failures?
- As returned `error` values — 5 sites in the snippet check `err` before using other results.
- What does Probe TCP Readiness With DialTimeout print when run?
- Invoke the file as-is — the `listen:`, `readiness check failed:`, `readiness ok:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.