Golang Panic Handler Middleware

sunday-snippet · Feb 6, 2022 · ~1 min
Sunday Snippet #3 golang panic handler middleware
Sunday Snippet #3 golang panic handler middleware

Handling panic elegantly:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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()))
}
· · ·

Love This Content?

Any kind of supports is greatly appreciated! Kindly support me via Bitcoin, Ko-fi, Trakteer, or just continue to read another content. You can write a response via Webmention and let me know the URL via Telegraph.

Drop Your Comment Below