将发送 OK 头部的代码放在 io.Pipe 写入数据后的地方
示例代码:
package main
import ( "io" "net/http" )
func main() { pr, pw := io.Pipe()
// 将发送 OK 头部的代码放在 io.Pipe 写入数据后的地方
go func() {
defer pw.Close()
pw.Write([]byte("Hello, World!"))
}()
handler := func(w http.ResponseWriter, req *http.Request) {
// 在 io.Pipe 读取数据之前等待
<-pr.Ready
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
io.Copy(w, pr)
}
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}