You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
31 lines
1.0 KiB
Go
31 lines
1.0 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
)
|
|
|
|
// recoverPanic provides middleware for recovering from panics in the same goroutine that
|
|
// executred the recoverPanic middleware.
|
|
//
|
|
// This means that panics from goroutines created in handler operations will still need
|
|
// to be handled separately.Failure to do so will cause the application to exit and bring
|
|
// down the server.
|
|
func (app *application) recoverPanic(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// Create a deferred function (which will always be run in the event of a panic
|
|
// as Go unwinds the stack).
|
|
defer func() {
|
|
if err := recover(); err != nil {
|
|
// If there was a panic, set a "Connection: close" header on the
|
|
// response. This acts as a trigger to make Go's HTTP server
|
|
// automatically close the current connection after a response has been
|
|
// sent.
|
|
w.Header().Set("Connection", "close")
|
|
app.serverErrorResponse(w, r, fmt.Errorf("%s", http.ErrAbortHandler))
|
|
}
|
|
}()
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|