本文介绍在Golang网络编程中,为HTTP请求或者TCP请求设置超时。这篇文章的内容来自PPT,所以文字不多,都是图片或者代码。
- Go网络编程基础
- 超时设置
- HTTP client/server
- TCP client/server
- KeepAlive
- TCP KeepAlive
- HTTP KeepAlive
- 调试方法
- Go网络编程基础
Socker编程:如下图所示
![](https://i-blog.csdnimg.cn/blog_migrate/47fe34bc2cb5f3a987dc3cce7f507637.jpeg)
HTTP编程:
Client示例如下:
transport := &http.Transport{
Dial: (&net.Dialer{
Timeout: 10 * time.Second,
}).Dial,
MaxIdleConns: 2,
}
client := &http.Client{
Timeout: time.Second * 30,
Transport: transport,
}
resp, _:= client.Get("http://localhost:8888/hello")
body, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
Server示例如下
http.HandleFunc("/hello", func(w http.ResponseWriter, req *http.Request){
fmt.Printf("receive msg form: %v", req.RemoteAddr)
_, _ := io.WriteString(w, "hello world!\n")
})
server := &http.Server{Addr: ":8888"}
_ := server.ListenAndServe()