超时处理程序将 ServeHTTP 执行转移到新的 goroutine 上,但在计时器结束后无法终止该 goroutine。对于每个请求,它都会创建两个 goroutine,但 ServeHTTP goroutine 永远不会用上下文杀死。
无法找到杀死 goroutine 的方法。
使用 time.Sleep 函数编辑For-loop,代表着巨大的计算量,超出了我们的计时器范围。可以用任何其他功能替换它。
package main
import (
"fmt"
"io"
"net/http"
"runtime"
"time"
)
type api struct{}
func (a api) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// For-loop block represents huge computation and usually takes more time
// Can replace with any code
i := 0
for {
if i == 500 {
break
}
fmt.Printf("#goroutines: %d\n", runtime.NumGoroutine())
time.Sleep(1 * time.Second)
i++
}
_, _ = io.WriteString(w, "Hello World!")
}
func main() {
var a api
s := http.NewServeMux()
s.Handle("/", a)
h := http.TimeoutHandler(s, 1*time.Second, `Timeout`)
fmt.Printf("#goroutines: %d\n", runtime.NumGoroutine())
_ = http.ListenAndServe(":8080", h)
}
ServeHTTP goroutine 应该与请求上下文一起终止,通常不会发生这种情况。
翻过高山走不出你
幕布斯7119047
相关分类