Go语言网络编程与Web应用开发
1. 网络错误处理
在Go语言中, net 包遵循常见约定返回 error 类型的错误。不过,部分错误实现还具备 net.Error 接口定义的额外方法,该接口定义如下:
package net
type Error interface {
Timeout() bool // Is the error a timeout?
Temporary() bool // Is the error temporary?
…
}
客户端代码可借助类型断言来检测 net.Error ,进而区分临时性网络错误和永久性网络错误。例如,网络爬虫在遇到临时性错误时可暂停并重试,否则放弃。示例代码如下:
// in a loop - some function returns an error err
if nerr, ok := err.(net.Error); ok && nerr.Temporary() {
time.Sleep(1e9)
continue // try again
}
if err != nil {
log.Fatal(err)
}
2. 简单Web服务器
2.1 启动Web服务器
HTTP是比TCP更高层的协议,它描述了Web服务器
超级会员免费看
订阅专栏 解锁全文

2772

被折叠的 条评论
为什么被折叠?



