简体   繁体   English

如果在http.HandlerFunc函数内发生紧急情况,它将不会发送到客户端http状态代码

[英]If a panic occurs within the http.HandlerFunc function, it will not be sent to the client http status code

If a panic occurs within the http.HandlerFunc function, it will not be sent to the client http status code. 如果在http.HandlerFunc函数内发生紧急情况,则不会将其发送到客户端http状态代码。 Why is this and how can it be avoided? 为什么会这样,如何避免呢? Because javascript XMLHttpRequest does not work well when it does not receive the http status code. 因为javascript XMLHttpRequest在未收到http状态代码时不能很好地工作。

How do we write an ajax request for situations where the http response has no state and no body content? 在http响应没有状态且没有正文内容的情况下,我们如何编写ajax请求?

func main() {
    var counter int

    http.HandleFunc("/hello", func(writer http.ResponseWriter, request *http.Request) {
        if counter%2 == 0 {
            counter++
            writer.Write([]byte(time.Now().String()))
        } else {
            counter++
            panic(":(")
        }
    })

    err := http.ListenAndServe(":9999", nil)
    if err != nil {
        panic(err)
    }
}

You should not use a panic in this case. 在这种情况下,您不应该惊慌。 Panic will cause the current go routine running the your handler func to exit without writing anything to the response which is not what you want, instead return an error code by using the WriteHeader method: 恐慌将导致运行您的处理程序函数的当前go例程退出,而不会在响应中写入任何您不想要的内容,而是使用WriteHeader方法返回错误代码:

func main() {
    var counter int

    http.HandleFunc("/hello", func(writer http.ResponseWriter, request *http.Request) {
        if counter%2 == 0 {
            counter++
            writer.Write([]byte(time.Now().String()))
        } else {
            counter++
            writer.WriteHeader(http.StatusInternalServerError)
        }
    })

    err := http.ListenAndServe(":9999", nil)
    if err != nil {
        panic(err)
    }
}

https://golang.org/pkg/net/http/#ResponseWriter https://golang.org/pkg/net/http/#ResponseWriter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM