goroutine not writing to channel

王林
Release: 2024-02-06 08:30:08
forward
775 people have browsed it

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)
}
Copy after login

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)
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template