amuz.es/src/infra/goutils@v0.1.3/handler/handler.go (about)

     1  package handler
     2  
     3  import (
     4  	"sync"
     5  	"context"
     6  	"log"
     7  )
     8  
     9  // 자식들을 기다리는 context waiter
    10  type Handler struct {
    11  	errorChan chan error
    12  	ctx       context.Context
    13  	canceler  context.CancelFunc
    14  	waiter    *sync.WaitGroup
    15  }
    16  
    17  func NewHandler(ctx context.Context) *Handler {
    18  	ctx, canceler := context.WithCancel(ctx)
    19  	return &Handler{
    20  		ctx:       ctx,
    21  		canceler:  canceler,
    22  		waiter:    &sync.WaitGroup{},
    23  		errorChan: make(chan error, 5),
    24  	}
    25  }
    26  
    27  func (h *Handler) NotifyError(err error) { h.errorChan <- err }
    28  func (h *Handler) Error() <-chan error   { return h.errorChan }
    29  func (h *Handler) Done() <-chan struct{} { return h.ctx.Done() }
    30  func (h *Handler) GracefulWait() {
    31  	if h.ctx.Err() == nil {
    32  		h.canceler()
    33  	}
    34  
    35  	h.waiter.Wait()
    36  	close(h.errorChan)
    37  
    38  	for remainError := range h.errorChan {
    39  		log.Println("remain errors ", remainError)
    40  	}
    41  }
    42  
    43  func (h *Handler) IncreaseWait() {
    44  	h.waiter.Add(1)
    45  }
    46  func (h *Handler) DecreaseWait() {
    47  	h.waiter.Done()
    48  }