我已经设置了竞赛编码的值,但我怎么能gzip模板,因为文件仍然很大。
func indexPageHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Encoding", "gzip")
r.Header.Set("Accept-Encoding", "gzip")
tmpl, err := template.New("index.html").ParseGlob("./templates/*")
if err != nil {
log.Println(err)
return
}
err = tmpl.Execute(w, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
是否有任何可以gzip响应的函数?]
根据建议,我改变了我的代码:
func indexPageHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Encoding", "gzip")
r.Header.Set("Accept-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
tmpl, err := template.New("index.html").ParseGlob("./templates/*")
if err != nil {
log.Println(err)
return
}
err = tmpl.Execute(gz, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
但是当我查询网址时,我只下载了gzip文件。它有什么问题?
答案 0 :(得分:1)
您可以使用包compress/gzip
:
func NewWriter(w io.Writer)*作家
NewWriter返回一个新的Writer 写入返回的编写器将被压缩并写入w。
在WriteCloser上调用Close是调用者的责任 完成后。写入可以缓冲,直到关闭才刷新。
在您的代码中,它可能如下所示:
gz := gzip.NewWriter(w)
defer gz.Close()
err = tmpl.Execute(gz, nil)
if err != nil {
http.Error(gz, err.Error(), http.StatusInternalServerError)
return
}
<强>聚苯乙烯。强>
您可能需要检查请求中的Accept-Encoding
标头,以查看浏览器是否接受gzip编码内容。
答案 1 :(得分:1)
r.Header.Set("Accept-Encoding", "gzip")
在请求上设置标头无效。您可能希望阅读此标头以确定是否使用gzip。
浏览器下载文件而不是呈现文件的原因是它缺少内容类型。当您在不设置Content-Type的情况下写入http.ResponseWriter时,会有一种算法确定Content-Type并设置正确的标头。但是随着你的身体被压缩,它无法确定正确的内容类型。在将任何数据写回客户端之前添加此项:
w.Header().Set("Content-Type", "text/html")
答案 2 :(得分:0)
这有点迟了,但我希望其他人会觉得有用。
该代码有效,但是您需要设置标题以使其被浏览器正确解释:
w.Header().Add("Content-Type","text/html")
w.Header().Add("Content-Encoding","gzip")
答案 3 :(得分:-1)
无论如何,我还没有解决这个问题。正如我所提到的,当我添加此代码时,重新启动服务器并查询此URL,我实际上下载了zip文件!?
最后,我使用Nginx制作反向代理来压缩模板。它有效。
还要感谢@Anisus