Golang channel didnt get closed

53 Views Asked by At

i am quite new with go especially channel. i tried to close a channel but it didn't get closed thus making method

fmt.Println("transaksi finaly done")

and

fmt.Println("order finaly done")

didn't get called by the program, what did i do wrong to exact?

full code


func (u *Usecase) GetOrderDetailByIDUsecase(ctx context.Context, orderId uint64) (*order.OrderPageDetailResponseDTO, error) {
    var wg sync.WaitGroup
    runtime.GOMAXPROCS(2)
    orderCh := make(chan *order.OrderResponseDTO)
    transaksiCh := make(chan *transaksi.TransaksiResponseDTO)
    errCh := make(chan error, 2)

    wg.Add(1)
    go func() {
        fmt.Println("order start")
        orderResp, err := u.orderController.GetOrderByID(ctx, orderId)
        fmt.Println("order done")
        errCh <- err
        orderCh <- orderResp
        fmt.Println("transaksi finaly done")
        wg.Done()
    }()

    wg.Add(1)
    go func() {
        fmt.Println("transaksi start")
        transaksiResp, err := u.transaksiController.GetTransaksiByID(ctx, int64(orderId))
        fmt.Println("transaksi done")
        errCh <- err
        transaksiCh <- transaksiResp
        fmt.Println("transaksi finaly done")
        wg.Done()
    }()

    go func() {
        wg.Wait()
        close(errCh)
        close(orderCh)
        close(transaksiCh)
    }()
    
    for err := range errCh {
        if err != nil {
            return nil, err
        }
    }

    var orderResp *order.OrderResponseDTO
    var transaksiResp *transaksi.TransaksiResponseDTO
    select {
    case orderResp = <-orderCh:
    case transaksiResp = <-transaksiCh:
    }

    return &order.OrderPageDetailResponseDTO{
        Order:     orderResp,
        Transaksi: transaksiResp,
    }, nil
}
1

There are 1 best solutions below

0
Stephen Newell On BEST ANSWER

Your "producer" goroutines are blocked on orderCh and transaksiCh. Since you didn't give them a size in the call to make, the write will block until somebody is ready to read it. The same goroutine that reads those channels waits for errCh to close, but that depends on the producer goroutines both finishing because of your WaitGroup.