【发布时间】:2018-02-22 11:02:58
【问题描述】:
我在底部的示例中创建了一个在端口 3000 上运行的小服务器。您可以通过“htto://localhost:3000/time”访问它。整个 Request 被两个中间件覆盖。第一个“cancelHandler”和第二个“otherHandler”被调用——它在 4 秒后响应一些虚拟数据。
我的问题:当我在浏览器中请求页面然后取消请求时(在 4 秒之前)。服务器仍在后台处理 goroutine/请求。我已经花了几个小时在谷歌上找到一个解决方案,但我无法理解上下文。 (context.WithCancel()) 我知道我必须创建一个 chan 并收听它,但这如何处理请求。那已经是一个 goroutine,我是否必须在 request/goroutine 中创建另一个 goroutine?还有一个问题是,我真的应该为此使用 Context 还是使用 cancelNotifier 有更简单的解决方案?
也许有人可以为我和其他可能有相同理解问题的人描述它。
解决方案应该是cancel Handler在停止goroutine/request,当浏览器取消请求时。
非常感谢您的宝贵时间!
package main
import (
"log"
"net/http"
"time"
"fmt"
)
func otherHandler(format string) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Duration(4)*time.Second)
tm := time.Now().Format(format)
w.Write([]byte("The time is: " + tm))
fmt.Println("response:", "The time is: "+tm)
}
return http.HandlerFunc(fn)
}
func cancelHandler(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
fmt.Println("start: called cancelHandler")
h.ServeHTTP(w, r)
fmt.Println("end: called cancelHandler")
}
return http.HandlerFunc(fn)
}
func main() {
mux := http.NewServeMux()
th := otherHandler(time.RFC1123)
mux.Handle("/time", cancelHandler(th))
log.Println("Listening...")
http.ListenAndServe(":3000", mux)
}
【问题讨论】:
标签: go server middleware