https://github.com/gowww/fatal
🚑 A handler that recovers from panics
https://github.com/gowww/fatal
fatal go golang handler http middleware panic recover
Last synced: 29 days ago
JSON representation
🚑 A handler that recovers from panics
- Host: GitHub
- URL: https://github.com/gowww/fatal
- Owner: gowww
- License: mit
- Created: 2017-06-04T22:58:20.000Z (almost 9 years ago)
- Default Branch: master
- Last Pushed: 2026-01-27T18:25:55.000Z (2 months ago)
- Last Synced: 2026-01-28T04:53:01.251Z (2 months ago)
- Topics: fatal, go, golang, handler, http, middleware, panic, recover
- Language: Go
- Homepage:
- Size: 10.7 KB
- Stars: 8
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# [](https://github.com/gowww) fatal [](https://godoc.org/github.com/gowww/fatal) [](https://travis-ci.org/gowww/fatal) [](https://coveralls.io/github/gowww/fatal?branch=master) [](https://goreportcard.com/report/github.com/gowww/fatal) 
Package [fatal](https://godoc.org/github.com/gowww/fatal) provides a handler that recovers from panics.
## Installing
1. Get package:
```Shell
go get -u github.com/gowww/fatal
```
2. Import it in your code:
```Go
import "github.com/gowww/fatal"
```
## Usage
To wrap an [http.Handler](https://golang.org/pkg/net/http/#Handler), use [Handle](https://godoc.org/github.com/gowww/fatal#Handle):
```Go
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
panic("error")
})
http.ListenAndServe(":8080", fatal.Handle(mux, nil))
```
To wrap an [http.HandlerFunc](https://golang.org/pkg/net/http/#HandlerFunc), use [HandleFunc](https://godoc.org/github.com/gowww/fatal#HandleFunc):
```Go
http.Handle("/", fatal.HandleFunc(func(w http.ResponseWriter, r *http.Request) {
panic("error")
}, nil))
http.ListenAndServe(":8080", nil)
```
### Custom "error" handler
When your code panics, the response status is set to 500 and an empty body is sent by default.
But you can set your own error handler and retrive the error value with [Error](https://godoc.org/github.com/gowww/fatal#Error).
In this case, it's up to you to set the response status code (normally 500):
```Go
http.ListenAndServe(":8080", fatal.Handle(mux, &fatal.Options{
RecoverHandler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "error: %v", fatal.Error(r))
}),
}))
```