Add handling if mp4 client drops connection

This commit is contained in:
Alex X
2024-05-29 17:32:11 +03:00
parent a9e7a73cc8
commit 2ab1d9d774
+14 -13
View File
@@ -1,6 +1,7 @@
package mp4 package mp4
import ( import (
"context"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
@@ -127,20 +128,20 @@ func handlerMP4(w http.ResponseWriter, r *http.Request) {
header.Set("Content-Disposition", `attachment; filename="`+filename+`"`) header.Set("Content-Disposition", `attachment; filename="`+filename+`"`)
} }
var duration *time.Timer ctx := r.Context() // handle when the client drops the connection
if s := query.Get("duration"); s != "" {
if i, _ := strconv.Atoi(s); i > 0 { if i := core.Atoi(query.Get("duration")); i > 0 {
duration = time.AfterFunc(time.Second*time.Duration(i), func() { timeout := time.Second * time.Duration(i)
_ = cons.Stop() var cancel context.CancelFunc
}) ctx, cancel = context.WithTimeout(ctx, timeout)
} defer cancel()
} }
go func() {
<-ctx.Done()
_ = cons.Stop()
stream.RemoveConsumer(cons)
}()
_, _ = cons.WriteTo(w) _, _ = cons.WriteTo(w)
stream.RemoveConsumer(cons)
if duration != nil {
duration.Stop()
}
} }