Skip to content

Instantly share code, notes, and snippets.

@maraino
Last active January 30, 2020 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maraino/2504d3948f36802e6c1fa31a06cbb766 to your computer and use it in GitHub Desktop.
Save maraino/2504d3948f36802e6c1fa31a06cbb766 to your computer and use it in GitHub Desktop.
Simple panic middleware
package main
import (
"log"
"net/http"
)
func panicMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if e := recover(); e != nil {
w.WriteHeader(http.StatusInternalServerError)
if s, ok := e.(string); ok {
w.Write([]byte(s))
}
}
}()
next.ServeHTTP(w, r)
})
}
func main() {
server := &http.Server{
Addr: ":8080",
Handler: panicMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.RequestURI {
case "/error":
panic("something bad happened")
default:
w.Write([]byte("Hello World!\n"))
}
})),
}
log.Fatal(server.ListenAndServe())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment