mirror of
https://github.com/bluenviron/mediamtx.git
synced 2026-01-09 20:02:01 -08:00
stop execution in case of panics when handling HTTP requests (#2021)
This commit is contained in:
parent
64a715a663
commit
f0a4bd4e5d
1 changed files with 23 additions and 1 deletions
|
|
@ -3,9 +3,12 @@ package core
|
|||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/bluenviron/mediamtx/internal/conf"
|
||||
|
|
@ -17,6 +20,25 @@ func (nilWriter) Write(p []byte) (int, error) {
|
|||
return len(p), nil
|
||||
}
|
||||
|
||||
// exit when there's a panic inside HTTP handlers.
|
||||
// https://github.com/golang/go/issues/16542
|
||||
type exitOnPanicHandler struct {
|
||||
http.Handler
|
||||
}
|
||||
|
||||
func (h exitOnPanicHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
err := recover()
|
||||
if err != nil {
|
||||
buf := make([]byte, 1<<20)
|
||||
n := runtime.Stack(buf, true)
|
||||
fmt.Fprintf(os.Stderr, "panic: %v\n\n%s", err, buf[:n])
|
||||
os.Exit(1)
|
||||
}
|
||||
}()
|
||||
h.Handler.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
type httpServer struct {
|
||||
ln net.Listener
|
||||
inner *http.Server
|
||||
|
|
@ -50,7 +72,7 @@ func newHTTPServer(
|
|||
s := &httpServer{
|
||||
ln: ln,
|
||||
inner: &http.Server{
|
||||
Handler: handler,
|
||||
Handler: exitOnPanicHandler{handler},
|
||||
TLSConfig: tlsConfig,
|
||||
ReadHeaderTimeout: time.Duration(readTimeout),
|
||||
ErrorLog: log.New(&nilWriter{}, "", 0),
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue