Last active
January 30, 2020 19:46
-
-
Save maraino/2504d3948f36802e6c1fa31a06cbb766 to your computer and use it in GitHub Desktop.
Simple panic middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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