doulin6448 2015-10-11 16:55
浏览 20

如何使用Revel框架执行HTML Minify

My first idea was to get the response body within the filter, then use one of minify libraries like tdewolff/minify and write to response, but i cant find the way to get response body. Is there any better solutions?

  • 写回答

1条回答 默认 最新

  • drsxzut183207938 2015-10-11 23:02
    关注

    It seems, by looking at the docs, that a filter can access the Controller type, which contains the Response. This response contains Out which is a ResponseWriter (and thus also an io.Writer). We need to replace only the Write method to redirect the write to the minifier, which then writes to the response writer. We need to use io.Pipe and a goroutine for this.

    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}
    }
    

    Something along those lines (not tested). Here we take the incoming io.Writer (which is part of the ResponseWriter), and wrap a struct around that. It keeps the original methods for the response writer, but the Write method is overrided to be replaced by the PipeWriter. This means that any write to the new response writer goes to PipeWriter, which is coupled to PipeReader. Minify Reads from that reader and writes to the original response writer.

    Because we change the value of c.Response.Out, we need to pass it explicitly to the goroutine. Make sure you obtain the correct mimetype (through extension?) or call the appropriate minify function directly.

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100