Go 如何使用Revel框架执行html缩小

Go 如何使用Revel框架执行html缩小,go,revel,Go,Revel,我的第一个想法是在过滤器中获取响应体,然后使用一个小型库,如tdewolff/minify和write to response,但我找不到获取响应体的方法。 有更好的解决方案吗?通过查看文档,过滤器似乎可以访问包含响应的控制器类型。此响应包含Out,Out是响应编写器,因此也是io.Writer。我们只需要替换Write方法,将写入重定向到minifier,然后minifier将写入响应编写器。我们需要使用io.Pipe和goroutine来实现这一点 type MinifyResponseWr

我的第一个想法是在过滤器中获取响应体,然后使用一个小型库,如tdewolff/minify和write to response,但我找不到获取响应体的方法。
有更好的解决方案吗?

通过查看文档,过滤器似乎可以访问包含响应的控制器类型。此响应包含Out,Out是响应编写器,因此也是io.Writer。我们只需要替换Write方法,将写入重定向到minifier,然后minifier将写入响应编写器。我们需要使用io.Pipe和goroutine来实现这一点

type MinifyResponseWriter struct {
    http.ResponseWriter
    io.Writer
}

func (f MinifyResponseWriter) Write(b []byte) (int, error) {
    return f.Writer.Write(b)
}

func MinifyFilter(c *Controller, fc []Filter) {
    pr, pw := io.Pipe()
    go func(w io.Writer) {
        m := minify.New()
        m.AddFunc("text/css", css.Minify)
        m.AddFunc("text/html", html.Minify)
        m.AddFunc("text/javascript", js.Minify)
        m.AddFunc("image/svg+xml", svg.Minify)
        m.AddFuncRegexp(regexp.MustCompile("[/+]json$"), json.Minify)
        m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify)

        if err := m.Minify("mimetype", w, pr); err != nil {
            panic(err)
        }
    }(c.Response.Out)
    c.Response.Out = MinifyResponseWriter{c.Response.Out, pw}
}
这方面的东西没有经过测试。在这里,我们获取作为ResponseWriter一部分的传入io.Writer,并围绕它包装一个结构。它保留响应编写器的原始方法,但重写写入方法以被PipeWriter替换。这意味着对新响应编写器的任何写入都将转到PipeWriter,它与PipeReader耦合。Minify从该读卡器读取并写入原始响应编写器


因为我们更改了c.Response.Out的值,所以需要显式地将其传递给goroutine。确保通过扩展获得正确的mimetype?或者直接调用相应的缩小功能。

它在Firefox中工作,但Chrome不会显示错误为net::ERR\u CONTENT\u LENGTH\u不匹配的页面。尝试在revel.CompressFilter之前或之后插入筛选器,但未成功。我不确定revel是如何工作的,但请看一看,您似乎需要删除内容长度标题以便重新计算?非常感谢您的大力帮助和出色的缩小库。我看到的唯一问题是像goroutine 45[semacquire]这样的无休止的错误:sync.runtime\u Syncsemacquire0xc82013aa00/home/venom/gocode/src/github.com/tdewolff/buffer/shifter.go:75在我更新页面10次之后谢谢!这是一个奇怪的错误,从行号来看,它似乎来自给定io.Reader的Read函数。也许是因为管道没有关好?如果没有更多信息,就无法确定。111行是:if err:=m.Minifytext/html,w,pr;呃!=nil{panicerr}错误:Conn.Write写入的内容超过声明的内容长度;goroutine 56[运行]:我的站点/app.glob.func3.10xc820281810、0xc820276b28、0x7f834fdb4100、0xc820281760/home/venom/gocode/src/my site/app/init.go:111+0x666由我的站点/app.glob.func3/home/venom/gocode/src/my site/app/init.go:114+0x2f4创建