2 回答
TA贡献1995条经验 获得超2个赞
您可以通过引入外循环来消除 goto。如果打开连接出错,则继续外循环。如果读取行出错,则跳出内部循环。
完成后关闭连接。defer 在函数返回之前不会执行。
func Reader(source string, proto string, chOutput chan string) {
for {
fmt.Println("Conectando con Source:", source)
conn, err := net.Dial(proto, source)
if err != nil {
fmt.Println("Error:", err.Error())
time.Sleep(1 * time.Second)
continue
}
reader := bufio.NewReader(conn)
for {
line, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error:", err.Error())
conn.Close()
time.Sleep(1 * time.Second)
break
}
fmt.Println("Enviando dato a Buffer:", line)
chOutput <- line
}
}
}
考虑在连接失败时使用指数退避:
func Reader(source string, proto string, chOutput chan string) {
sleep := time.Second
for {
fmt.Println("Conectando con Source:", source)
conn, err := net.Dial(proto, source)
if err != nil {
fmt.Println("Error:", err.Error())
sleep *= 2 // exponential backoff
if sleep > time.Minute {
sleep = time.Minute
}
time.Sleep(sleep)
continue
}
sleep = time.Second // Reset on success.
reader := bufio.NewReader(conn)
for {
line, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error:", err.Error())
conn.Close()
time.Sleep(sleep)
break
}
fmt.Println("Enviando dato a Buffer:", line)
chOutput <- line
}
}
}
- 2 回答
- 0 关注
- 229 浏览
添加回答
举报