1

I write some gin application

func (h Handler) GetOptions(context *gin.Context) {
    // skip
    outputChan := make(chan shipping.Results)
    inputChan := make(chan shipping.Option)

    var waitGroup sync.WaitGroup
    go handleResults(inputChan, outputChan)
    defer close(outputChan)

    for _, method := range request.CarrierCodes {
        waitGroup.Add(1)
        go calculateAsync(method, request, inputChan, &waitGroup)
    }

    waitGroup.Wait()
    close(inputChan)

    context.JSON(http.StatusOK, <-outputChan)
}

func handleResults(input <-chan shipping.ShippingOption, output chan<- shipping.ShippingResults) {
    var shipping shipping.ShippingResults
    for result := range input {
        shipping.Results = append(shipping.Results, result)
    }
    output <- shipping
}

func calculateAsync(method string, request *requestModel.RequestPayload, output chan<- shipping.ShippingOption, wg *sync.WaitGroup) {
    defer wg.Done()

    obj, err := model.GetCarrierMethod(method, request)
    if err != nil {
        log.Error(err)
        return
    }

    for _, result := range obj.Calculate() {
        output <- result
    }
}

there is two channels, handleResults() collects output result and finally gin send JSON array. it works fine

but is it possible to output an error (500 status) if there was panic() in at least one underlying function Calculate()?

Smirnov
  • 137
  • 3
  • 12
  • 3
    Yes: You have to recover from the panic in calculate and send information about that panic either via the output channel or some other mechanism to handleResults and output 500. – Volker Jun 27 '23 at 05:38
  • https://go.dev/play/p/vwj9grIXdSo – Peter Jun 27 '23 at 09:30

0 Answers0