简体   繁体   中英

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. 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.

How do we write an ajax request for situations where the http response has no state and no body content?

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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