如果请求在http.Server中超时,为什么在Firefox中无限期重复请求?

我正在使用golang设置超时的简单服务器。当运行的处理程序花费的时间超过超时时间时,如果我通过Firefox请求,该请求将无限期重复。但是,如果我使用Postman或curl,则不会重复请求。我想防止浏览器中的重复循环。

我尝试手动关闭请求正文或检查上下文是否已取消,但是这些方法均无效。

let cancelButton = searchBar.value(forKey: "cancelButton") as! UIButton
NotificationCenter.default.rx.notification(UIResponder.keyboardWillHideNotification)
    .map { _ in true }
    .take(1)
    .subscribe(cancelButton.rx.isEnabled)
    .disposed(by: disposeBag)

我希望处理程序退出并且不再重复。

pwlsiynice 回答:如果请求在http.Server中超时,为什么在Firefox中无限期重复请求?

据我所知,您面临的问题是服务器超时突然关闭了底层tcp conn,而没有编写适当的http响应,同时,当firefox检测到conn突然关闭时,似乎决定重试N次,可能因为它假设它遇到连接问题。

我相信解决方案是使用http.Handler来控制处理程序的处理持续时间,并在超时到期时返回正确的HTTP响应。

服务器超时应该更长,并且应用于防止异常的客户端行为,而不是处理程序的缓慢性。

标准的HTTP软件包为此提供了TimeoutHandler函数。

package main

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

func main() {
    slowHandler := func(w http.ResponseWriter,r *http.Request) {
        defer r.Body.Close()
        fmt.Printf("Hello,you've requested: %s\n",r.URL.Path)
        time.Sleep(time.Second * 2)
        fmt.Fprintf(w,"Hello,r.URL.Path)
    }
    http.HandleFunc("/",slowHandler)

    var handler http.Handler = http.DefaultServeMux
    handler = http.TimeoutHandler(handler,time.Second,"processing timeout")

    s := http.Server{
        Addr:    ":8080",Handler: handler,// ReadTimeout:  1 * time.Second,// WriteTimeout: 1 * time.Second,}
    s.ListenAndServe()
}
本文链接:https://www.f2er.com/3140711.html

大家都在问