git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/httpx/middlewarex/recover.go (about)

     1  package middlewarex
     2  
     3  import (
     4  	"net/http"
     5  )
     6  
     7  func Recoverer(next http.Handler) http.Handler {
     8  	fn := func(w http.ResponseWriter, r *http.Request) {
     9  		defer func() {
    10  			if rvr := recover(); rvr != nil {
    11  				if rvr == http.ErrAbortHandler {
    12  					// we don't recover http.ErrAbortHandler so the response
    13  					// to the client is aborted, this should not be logged
    14  					panic(rvr)
    15  				}
    16  
    17  				if r.Header.Get("Connection") != "Upgrade" {
    18  					w.WriteHeader(http.StatusInternalServerError)
    19  				}
    20  			}
    21  		}()
    22  
    23  		next.ServeHTTP(w, r)
    24  	}
    25  
    26  	return http.HandlerFunc(fn)
    27  }