实现说明
逻辑集中在函数 probe、main里。
错误处理是内联的:5 处测试 err != nil 并立即分支。入口处 defer、出口处执行:defer 让清理与获取紧挨着写。
使用要点
- 没有可捕获的异常——每个调用点都必须检查
err返回值。 - 跑完文件,输出里会留下标记——
listen:、readiness check failed:、readiness ok:。 main的演示流程是probe——跑一遍文件,这条流程从头到尾可见。
常见问题
调用方该如何处理失败?
以返回的 error 值上报——示例里 5 处在使用其他结果前先检查 err。
运行「用 DialTimeout 探测 TCP 就绪」会打印什么?
整个文件跑完,输出行以 listen:、readiness check failed:、readiness ok: 这类前缀开头。
签名一览:func probe(addr string, budget time.Duration) error
核心语句
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()
代码示例
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)
}
}