github.com/hellobchain/third_party@v0.0.0-20230331131523-deb0478a2e52/go-chi/chi/middleware/recoverer.go (about) 1 package middleware 2 3 // The original work was derived from Goji's middleware, source: 4 // https://github.com/zenazn/goji/tree/master/web/middleware 5 6 import ( 7 "fmt" 8 "os" 9 "runtime/debug" 10 11 "github.com/hellobchain/newcryptosm/http" 12 ) 13 14 // Recoverer is a middleware that recovers from panics, logs the panic (and a 15 // backtrace), and returns a HTTP 500 (Internal Server Error) status if 16 // possible. Recoverer prints a request ID if one is provided. 17 // 18 // Alternatively, look at https://github.com/pressly/lg middleware pkgs. 19 func Recoverer(next http.Handler) http.Handler { 20 fn := func(w http.ResponseWriter, r *http.Request) { 21 defer func() { 22 if rvr := recover(); rvr != nil { 23 24 logEntry := GetLogEntry(r) 25 if logEntry != nil { 26 logEntry.Panic(rvr, debug.Stack()) 27 } else { 28 fmt.Fprintf(os.Stderr, "Panic: %+v\n", rvr) 29 debug.PrintStack() 30 } 31 32 http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) 33 } 34 }() 35 36 next.ServeHTTP(w, r) 37 } 38 39 return http.HandlerFunc(fn) 40 }