英文:
goroutine not writting to channel
问题
我是你的中文翻译助手,以下是代码的翻译:
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)
}
在goroutine中,pdf
从GenerateFromHTML
接收到值,但buf
没有接收到任何值,因此这段代码所在的函数返回了一个大小为0的字节。
如果有任何问题,请随时提问。谢谢!
英文:
I'm new to Go and I'm having a problem with the code below
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)
}
Inside the goroutine pdf
receives from GenerateFromHTML
but buf
doesn't receive any value and so the function this code is inside returns a byte with size 0.
Any help is much appreciated. Thanks in advance
答案1
得分: 1
这段代码是同步的。处理程序生成一个字节切片,并且当这些字节准备好时,应该使用c.Blob方法返回该切片。
发布的代码在goroutine中开始工作,不等待工作完成,并返回空的字节切片。
你可以通过移除goroutine来修复这个问题:
data, err := pdf.GenerateFromHTML(string(rawDecodedText))
if err == nil {
// 在这里处理错误
}
return c.Blob(http.StatusOK, MIMEApplicationPdf, data)
这段代码唯一的问题是将所有数据加载到内存中,但如果pdf.GenerateFromHTML
返回[]byte
,这是不可避免的。
如果需要的话,你可以通过更新pdf.GenerateFromHTML
以返回io.Reader
并使用c.Stream来改进它。
英文:
This code is synchronous by its nature. Handler produces a slice of bytes and should return that slice using c.Blob method when these bytes are ready.
Posted code starts work in goroutine, does not wait for that work completion and returns empty bytes slice.
You can fix that by removing goroutine:
data, err := pdf.GenerateFromHTML(string(rawDecodedText))
if err == nil {
// handle error here
}
return c.Blob(http.StatusOK, MIMEApplicationPdf, data)
The only issue with this code is loading all data in memory, but it is unavoidable if pdf.GenerateFromHTML
returns []byte
.
You can improve that if necessary by updating pdf.GenerateFromHTML
to return io.Reader
and use c.Stream.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论