如果连接丢失,golang停止处理程序如何运行

nbysray5  于 2023-01-18  发布在  Go
关注(0)|答案(1)|浏览(118)

看起来即使连接丢失了,处理程序功能仍然在运行,例如,如果我访问http://0.0.0.0:8000/home并突然关闭浏览器,屏幕将继续打印所有的数字。

package main

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

func main() {
    http.HandleFunc("/home", func(w http.ResponseWriter, r *http.Request) {
        i := 0
        for {
            fmt.Println("i", i)
            i++
            time.Sleep(time.Microsecond * 15)
        }
    })
    http.ListenAndServe(":8000", nil)
}

相关:How golang gin stop handler function immediately if connection is lost

ljsrvy3e

ljsrvy3e1#

备选案文1:在断开的连接上写入将返回错误。当fmt.println返回错误时,将从循环中中断。

func example(w http.ResponseWriter, r *http.Request) {
    i := 0
    for {
        _, err := fmt.Println("i", i)
        if err != nil {
            return
        }
        i++
        time.Sleep(time.Microsecond * 15)
    }
}

备选案文2:服务器在断开连接时取消请求上下文。在上下文未取消时循环。

func example(w http.ResponseWriter, r *http.Request) {
    i := 0
    c := r.Context()
    for c.Err() == nil {
        fmt.Println("i", i)
        i++
        time.Sleep(time.Microsecond * 15)
    }
}

备选案文3:服务器在断开连接时取消请求上下文。循环等待上下文取消或计时器。取消时退出。

func example(w http.ResponseWriter, r *http.Request) {
    t := time.NewTicker(time.Microsecond * 15)
    defer t.Stop()
    done := r.Context().Done()
    for {
        for {
            select {
            case <-done:
                fmt.Println("Done!")
                return
            case t := <-t.C:
                fmt.Println("Current time: ", t)
            }
        }
    }
}

处理程序将使用选项3提前返回。选项1和2始终等待休眠完成,然后处理程序返回。

相关问题