Home >Backend Development >Golang >goroutine not writing to channel

goroutine not writing to channel

王林
王林forward
2024-02-06 08:30:08804browse

goroutine 未写入通道

Question content

I am new to go and I have a problem using the following code

func (h *Handler) GeneratePdfFromHTML(c echo.Context) (err error) {
    req := &createPdfFromHTMLRequest{}
    if err := req.bind(c); err != nil {
        return c.JSON(http.StatusBadRequest, utils.NewError(err))
    }

    rawDecodedText, err := base64.StdEncoding.DecodeString(req.HTML)
    if err != nil {
        return c.JSON(http.StatusInternalServerError, utils.NewError(err))
    }

    buf := make(chan []byte)

    go func() {
        defer close(buf)
        pdf, err := pdf.GenerateFromHTML(string(rawDecodedText))
        if err == nil {
            buf <- pdf
        }
    }()

    if err != nil {
        return c.JSON(http.StatusInternalServerError, utils.NewError(err))
    }

    return c.Blob(http.StatusOK, MIMEApplicationPdf, <-buf)
}

Receive information from generatefromhtml in goroutine pdf, but buf does not receive any value, so the function where this code is located returns a size of 0 byte.

Any help is greatly appreciated. Thanks in advance


Correct answer


This code is synchronous in nature. The handler generates a slice of bytes and should use the c.blob method to return that slice when these bytes are ready.

The posted code starts work in a goroutine, does not wait for the work to complete and returns a null byte slice.

You can solve this problem by removing the goroutine:

data, err := pdf.GenerateFromHTML(string(rawDecodedText))
if err == nil {
    // handle error here
}
return c.Blob(http.StatusOK, MIMEApplicationPdf, data)

The only problem with this code is loading all the data into memory, but this is unavoidable if pdf.generatefromhtml returns []byte. If necessary, you can improve this by updating pdf.generatefromhtml to return io.reader and using c.stream.

The above is the detailed content of goroutine not writing to channel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete