This content originally appeared on DEV Community and was authored by Clavin June
Handling panic elegantly:
package main
import (
"fmt"
"log"
"net/http"
)
func handle() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
panic("i am panic")
}
}
func handlePanic(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer func() {
if i := recover(); i != nil {
log.Printf("panic at %s: %v", r.URL.Path, i)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, http.StatusText(http.StatusInternalServerError))
}
}()
next(w, r)
}
}
func main() {
http.ListenAndServe(":8000", handlePanic(handle()))
}
This content originally appeared on DEV Community and was authored by Clavin June
Print
Share
Comment
Cite
Upload
Translate
Updates
There are no updates yet.
Click the Upload button above to add an update.
![](https://www.radiofree.org/wp-content/plugins/print-app/icon.jpg)
APA
MLA
Clavin June | Sciencx (2022-02-05T17:10:15+00:00) Golang Panic Handler Middleware. Retrieved from https://www.scien.cx/2022/02/05/golang-panic-handler-middleware/
" » Golang Panic Handler Middleware." Clavin June | Sciencx - Saturday February 5, 2022, https://www.scien.cx/2022/02/05/golang-panic-handler-middleware/
HARVARDClavin June | Sciencx Saturday February 5, 2022 » Golang Panic Handler Middleware., viewed ,<https://www.scien.cx/2022/02/05/golang-panic-handler-middleware/>
VANCOUVERClavin June | Sciencx - » Golang Panic Handler Middleware. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/02/05/golang-panic-handler-middleware/
CHICAGO" » Golang Panic Handler Middleware." Clavin June | Sciencx - Accessed . https://www.scien.cx/2022/02/05/golang-panic-handler-middleware/
IEEE" » Golang Panic Handler Middleware." Clavin June | Sciencx [Online]. Available: https://www.scien.cx/2022/02/05/golang-panic-handler-middleware/. [Accessed: ]
rf:citation » Golang Panic Handler Middleware | Clavin June | Sciencx | https://www.scien.cx/2022/02/05/golang-panic-handler-middleware/ |
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.