Browse Source

stop execution in case of panics when handling HTTP requests (#2021)

pull/2024/head
Alessandro Ros 3 years ago committed by GitHub
parent
commit
f0a4bd4e5d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 24
      internal/core/http_server.go

24
internal/core/http_server.go

@ -3,9 +3,12 @@ package core @@ -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) { @@ -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( @@ -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…
Cancel
Save