DEV Community

Clavin June
Clavin June

Posted on • Originally published at clavinjune.dev on

3 2

Golang Panic Handler Middleware

Sunday Snippet #2 go get golang private module

Handling panic elegantly:

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()))
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more