• Kirill Smelkov's avatar
    xcontext: New package that complements std package context. · 8e09e376
    Kirill Smelkov authored
    Quoting documentation:
    
    """
    Package xcontext provides addons to std package context.
    
    Merging contexts
    
    Merge could be handy in situations where spawned job needs to be canceled
    whenever any of 2 contexts becomes done. This frequently arises with service
    methods that accept context as argument, and the service itself, on another
    control line, could be instructed to become non-operational. For example:
    
    	func (srv *Service) DoSomething(ctx context.Context) (err error) {
    		defer xerr.Contextf(&err, "%s: do something", srv)
    
           		// srv.serveCtx is context that becomes canceled when srv is
           		// instructed to stop providing service.
           		origCtx := ctx
           		ctx, cancel := xcontext.Merge(ctx, srv.serveCtx)
           		defer cancel()
    
           		err = srv.doJob(ctx)
           		if err != nil {
           			if ctx.Err() != nil && origCtx.Err() == nil {
           				// error due to service shutdown
           				err = ErrServiceDown
           			}
           			return err
           		}
    
    		...
    	}
    """
    8e09e376
xcontext.go 6.46 KB