You can use example below to recover from panic and let your HTTP server carry on serving requests otherwise it will crash. Any panic is a kind of internal error so we will return 500 response in such case.


Middleware


If you cause a panic on purpose in one of your endpoints and call it, you will see that the response will be 500 Internal Server Error.


package pkg

import (
"net/http"
)

func PanicRecovery(handler http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, rq *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Error(err)

// To avoid 'superfluous response.WriteHeader call' error
if rw.Header().Get("Content-Type") == "" {
rw.WriteHeader(http.StatusInternalServerError)
}
}
}()

handler.ServeHTTP(rw, rq)
})
}

return &http.Server{Addr: ":8080", Handler: pkg.PanicRecovery(yourRouter)}