github.com/searKing/golang/go@v1.2.117/context/func.go (about)

     1  // Copyright 2023 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package context
     6  
     7  import (
     8  	"context"
     9  )
    10  
    11  // WrapFunc returns a function literal that uses ctx to
    12  // wait for the f parameter to be called and executed done
    13  // or return immediately with f not terminate if ctx done.
    14  // f will not be terminated if it's called.
    15  func WrapFunc(ctx context.Context, f func() error) func() error {
    16  	return func() (err error) {
    17  		doneC := make(chan struct{})
    18  		go func() {
    19  			defer close(doneC)
    20  			err = f()
    21  		}()
    22  
    23  		select {
    24  		case <-doneC:
    25  			return nil
    26  		case <-ctx.Done():
    27  			return context.Cause(ctx)
    28  		}
    29  	}
    30  }