golang 笔记

golang 的坑

package main

import (
    "fmt"
    "net/http"
    "time"
)

func Hello(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello!!\n"))
    time.Sleep(10 * time.Second)
}

func main() {
    http.HandleFunc("/hello", Hello)
    addr := "0.0.0.0:8083"
    if err := http.ListenAndServe(addr, nil); err != nil {
        fmt.Println(err)
        return
    }
}

ResponseWriter.Write只是将数据写进了一个缓冲区,如过缓冲区未被写满是不会往tcp连接里写的,表现为包没发出去。http server会在Handler函数结束后调用Flush,所以在Handler函数里的任何阻塞行为都会影响到回包数据的发送。
有两种方法来规避:
主动调用Flush
w.(http.Flusher).Flush()
将长操作用go包起来
go func() { time.Sleep(10*time.Second) }()

猜你喜欢

转载自www.cnblogs.com/dh-dh/p/9121699.html