dongza1708 2018-02-22 11:02
浏览 151


I created in the example at the bottom a little server which is running on port 3000. You can access it over "htto://localhost:3000/time". The whole Request is covered with two middlewares. First "cancelHandler" and Second "otherHandler" is called - which is responding with some dummy data after 4 seconds.

To my problem: When i request the page in a browser and then cancel the request (before the 4sec). The server is still handling the goroutine/request in the background. I spent already hours to find a solution on google but i can just not wrap my head around the context. (context.WithCancel()) I get that i have to create a chan and listen to it but how does this work with the requests. thats already a goroutine, do i have to create another goroutine in the request/goroutine? Also another question is, should i really use Context for that or is there an easier solution with the cancelNotifier?

Maybe someone can describe it for me and others which maybe have the same understanding problem.

Solution should be that the cancel Handler is stopping the goroutine/request, when the browser cancels the request.

Thank you very much for your time!

package main

import (

func otherHandler(format string) http.Handler {
    fn := func(w http.ResponseWriter, r *http.Request) {
        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))

    http.ListenAndServe(":3000", mux)
  • 写回答



      相关推荐 更多相似问题


      • ¥30 关于#网络安全#的问题:非对称加密验证
      • ¥20 关于线性代数里施密特正交化和QR分解的疑问
      • ¥15 matlab超类包含解析错误
      • ¥15 python拖拽文件问题
      • ¥15 执行import paddle代码出现错误如何解决?
      • ¥15 hisat2align exited with value 137
      • ¥15 寻找大学生合作开发软件(Delphi)
      • ¥30 AndroidBench&eMMC内存测试速度&Android
      • ¥15 W10 文件共享失败 怎么解决
      • ¥20 b站私信完整导出的方法