Golang Panic Handler Middleware

sunday-snippet · 27 Okt 2022 · ~1 menit
Sunday Snippet #3 golang panic handler middleware
Sunday Snippet #3 golang panic handler middleware

Mengatasi panic dengan elegant:

 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()))
}
· · ·

Suka Konten Ini?

Bentuk dukungan apapun saya hargai! Dukung saya melalui Bitcoin, Ko-fi, Trakteer, atau lanjut baca konten saya yang lainnya. Kamu bisa menulis respon lewat Webmention dan beritahu saya URLnya lewat Telegraph.

Tulis komentar anda di bawah