From 54fda3422e70540f14edd8db1504cf09b92edfbc Mon Sep 17 00:00:00 2001 From: Nick Craig-Wood Date: Thu, 4 Jun 2020 12:02:48 +0100 Subject: [PATCH] atexit: implement OnError for cancelling multpart uploads --- lib/atexit/atexit.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/lib/atexit/atexit.go b/lib/atexit/atexit.go index 1976d5a2a..d52d50371 100644 --- a/lib/atexit/atexit.go +++ b/lib/atexit/atexit.go @@ -77,3 +77,23 @@ func Run() { } }) } + +// OnError registers fn with atexit and returns a function which +// runs fn() if *perr != nil and deregisters fn +// +// It should be used in a defer statement normally so +// +// defer OnError(&err, cancelFunc)() +// +// So cancelFunc will be run if the function exits with an error or +// at exit. +func OnError(perr *error, fn func()) func() { + handle := Register(fn) + return func() { + defer Unregister(handle) + if *perr != nil { + fn() + } + } + +}