英文:
Anyway to compress HTML output with Martini?
问题
在准嵌入式环境中,速度至关重要。我发现如果压缩我的 .html 文件,应用程序会更快。在 Martini 中是否有一个标志或方法可以实时进行这样的压缩?
英文:
In a quasi-embedded environment so speed is everything. I have found that if I compress my .html files, the app is speedier. Is there a flag or way in Martini to do this on the fly?
答案1
得分: 5
你可以使用gzip
中间件。
https://github.com/codegangsta/martini-contrib/tree/master/gzip
import (
"github.com/codegangsta/martini"
"github.com/codegangsta/martini-contrib/gzip"
)
func main() {
m := martini.Classic()
// 对每个请求进行gzip压缩
m.Use(gzip.All())
m.Run()
}
英文:
You can use gzip
Middleware
https://github.com/codegangsta/martini-contrib/tree/master/gzip
import (
"github.com/codegangsta/martini"
"github.com/codegangsta/martini-contrib/gzip"
)
func main() {
m := martini.Classic()
// gzip every request
m.Use(gzip.All())
m.Run()
}
答案2
得分: 5
这个答案只是为了展示@fabrizioM的答案实际上是有效的:
第一步:创建服务器
package main
import (
"github.com/codegangsta/martini"
"github.com/codegangsta/martini-contrib/gzip"
)
func main() {
m := martini.Classic()
// gzip every request
m.Use(gzip.All())
m.Get("/hello", func() string {
return "Hello, World!"
})
m.Run()
}
第二步:运行服务器
go run main.go
第三步:尝试服务器
这一步中,你必须记住包含Accept-Encoding: gzip
头部(或等效头部)。
没有压缩的情况下:
curl --dump-header http://localhost:3000/hello
HTTP/1.1 200 OK Date: Wed, 09 Jul 2014 17:19:35 GMT Content-Length: 13 Content-Type: text/plain; charset=utf-8 Hello, World!
使用压缩的情况下:
curl --dump-header http://localhost:3000/hello -H 'Accept-Encoding: gzip'
HTTP/1.1 200 OK Content-Encoding: gzip Content-Type: text/plain; charset=utf-8 Vary: Accept-Encoding Date: Wed, 09 Jul 2014 17:21:02 GMT Content-Length: 37 � n��Q��J
英文:
This answer is just to show that @fabrizioM's answer actually works:
Step 1: Create the server
package main
import (
"github.com/codegangsta/martini"
"github.com/codegangsta/martini-contrib/gzip"
)
func main() {
m := martini.Classic()
// gzip every request
m.Use(gzip.All())
m.Get("/hello", func() string {
return "Hello, World!"
})
m.Run()
}
Step 2: Run the server
go run main.go
Step 3: Try the server
This is the step where you must remember to include the Accept-Encoding: gzip
header (or equivalent).
Without compression:
curl --dump-header http://localhost:3000/hello
> HTTP/1.1 200 OK
> Date: Wed, 09 Jul 2014 17:19:35 GMT
> Content-Length: 13
> Content-Type: text/plain; charset=utf-8
>
> Hello, World!
With compression:
curl --dump-header http://localhost:3000/hello -H 'Accept-Encoding: gzip'
> HTTP/1.1 200 OK
> Content-Encoding: gzip
> Content-Type: text/plain; charset=utf-8
> Vary: Accept-Encoding
> Date: Wed, 09 Jul 2014 17:21:02 GMT
> Content-Length: 37
>
> � n��Q��J
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论