有一个可以立即使用的解决方案来对静态文件进行压缩并支持范围字节吗?
时间:2024-02-12
浏览:489
作者:佚名
有志者,事竟成!如果你在学习Golang,那么本文《有一个可以立即使用的解决方案来对静态文件进行压缩并支持范围字节吗?》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~
问题内容
我有发送静态文件的操作
func (ws *webserver) staticAction(w http.ResponseWriter, r *http.Request) bool {
staticFile, err := filepath.Abs(path.Join(ws.staticPath, path.Clean(r.URL.Path)))
if err == nil {
fi, err := os.Stat(staticFile)
if err == nil {
if mode := fi.Mode(); mode.IsRegular() {
http.ServeFile(w, r, staticFile)
return true
}
}
}
return false
}
需要压缩静态css和js。 http.servefile 支持范围字节,如果压缩从 http.servefile 返回的文件结构将被破坏。 我没有看到任何其他方法如何放弃范围字节,例如,通过删除客户端和服务器报告范围支持之间的标头或需要编写自己的解决方案 假设nginx之类的前端服务器不会安装
正确答案
这个库https://github.com/vearutop/statigz(我是作者)可以使用go1.16+的embed包提供预压缩资源,支持文件范围,无需额外配置。
package main
import (
"embed"
"log"
"net/http"
"github.com/vearutop/statigz"
"github.com/vearutop/statigz/brotli"
)
// Declare your embedded assets.
//go:embed static/*
var st embed.FS
func main() {
// Plug static assets handler to your server or router.
err := http.ListenAndServe(":80", statigz.FileServer(st, brotli.AddEncoding))
if err != nil {
log.Fatal(err)
}
}好了,本文到此结束,带大家了解了《有一个可以立即使用的解决方案来对静态文件进行压缩并支持范围字节吗?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.27
热门专题
