GZIP gin 中间件
Gin 中间件,用于启用 GZIP
支持。
使用方法
下载并安装:
go get github.com/gin-contrib/gzip
在代码中导入:
import "github.com/gin-contrib/gzip"
标准示例:
package main
import (
"fmt"
"net/http"
"time"
"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.Use(gzip.Gzip(gzip.DefaultCompression))
r.GET("/ping", func(c *gin.Context) {
c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix()))
})
// 在 0.0.0.0:8080 监听并服务
if err := r.Run(":8080"); err != nil {
log.Fatal(err)
}
}
自定义排除的扩展名
package main
import (
"fmt"
"net/http"
"time"
"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedExtensions([]string{".pdf", ".mp4"})))
r.GET("/ping", func(c *gin.Context) {
c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix()))
})
// 在 0.0.0.0:8080 监听并服务
if err := r.Run(":8080"); err != nil {
log.Fatal(err)
}
}
自定义排除的路径
package main
import (
"fmt"
"net/http"
"time"
"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedPaths([]string{"/api/"})))
r.GET("/ping", func(c *gin.Context) {
c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix()))
})
// 在 0.0.0.0:8080 监听并服务
if err := r.Run(":8080"); err != nil {
log.Fatal(err)
}
}
自定义排除的路径正则表达式
package main
import (
"fmt"
"net/http"
"time"
"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedPathsRegexs([]string{".*"})))
r.GET("/ping", func(c *gin.Context) {
c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix()))
})
// 在 0.0.0.0:8080 监听并服务
if err := r.Run(":8080"); err != nil {
log.Fatal(err)
}
}