Golang Panic Handler Middleware

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.Handl…


This content originally appeared on DEV Community and was authored by Clavin June

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


This content originally appeared on DEV Community and was authored by Clavin June


Print Share Comment Cite Upload Translate Updates
APA

Clavin June | Sciencx (2022-02-05T17:10:15+00:00) Golang Panic Handler Middleware. Retrieved from https://www.scien.cx/2022/02/05/golang-panic-handler-middleware/

MLA
" » Golang Panic Handler Middleware." Clavin June | Sciencx - Saturday February 5, 2022, https://www.scien.cx/2022/02/05/golang-panic-handler-middleware/
HARVARD
Clavin June | Sciencx Saturday February 5, 2022 » Golang Panic Handler Middleware., viewed ,<https://www.scien.cx/2022/02/05/golang-panic-handler-middleware/>
VANCOUVER
Clavin June | Sciencx - » Golang Panic Handler Middleware. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/02/05/golang-panic-handler-middleware/
CHICAGO
" » Golang Panic Handler Middleware." Clavin June | Sciencx - Accessed . https://www.scien.cx/2022/02/05/golang-panic-handler-middleware/
IEEE
" » Golang Panic Handler Middleware." Clavin June | Sciencx [Online]. Available: https://www.scien.cx/2022/02/05/golang-panic-handler-middleware/. [Accessed: ]
rf:citation
» Golang Panic Handler Middleware | Clavin June | Sciencx | https://www.scien.cx/2022/02/05/golang-panic-handler-middleware/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.