gzip middleware

This commit is contained in:
Nazar Kanaev 2021-04-02 17:28:41 +01:00
parent 82fdb3be6c
commit b082c3e048
2 changed files with 45 additions and 1 deletions

View File

@ -0,0 +1,42 @@
package gzip
import (
"compress/gzip"
"net/http"
"strings"
"github.com/nkanaev/yarr/src/server/router"
)
type gzipResponseWriter struct {
http.ResponseWriter
out *gzip.Writer
src http.ResponseWriter
}
func (rw *gzipResponseWriter) Header() http.Header {
return rw.src.Header()
}
func (rw *gzipResponseWriter) Write(x []byte) (int, error) {
return rw.out.Write(x)
}
func (rw *gzipResponseWriter) WriteHeader(statusCode int) {
rw.src.WriteHeader(statusCode)
}
func Middleware(c *router.Context) {
if strings.Contains(c.Req.Header.Get("Accept-Encoding"), "gzip") {
gz := &gzipResponseWriter{out: gzip.NewWriter(c.Out), src: c.Out}
defer gz.out.Close()
c.Out.Header().Set("Content-Encoding", "gzip")
c.Out = gz
c.Next()
return
}
c.Next()
}

View File

@ -14,6 +14,7 @@ import (
"github.com/nkanaev/yarr/src/content/sanitizer"
"github.com/nkanaev/yarr/src/content/silo"
"github.com/nkanaev/yarr/src/server/auth"
"github.com/nkanaev/yarr/src/server/gzip"
"github.com/nkanaev/yarr/src/server/opml"
"github.com/nkanaev/yarr/src/server/router"
"github.com/nkanaev/yarr/src/storage"
@ -23,6 +24,8 @@ import (
func (s *Server) handler() http.Handler {
r := router.NewRouter(s.BasePath)
r.Use(gzip.Middleware)
if s.Username != "" && s.Password != "" {
a := &auth.Middleware{
BasePath: s.BasePath,
@ -62,7 +65,6 @@ func (s *Server) handleIndex(c *router.Context) {
}
func (s *Server) handleStatic(c *router.Context) {
// TODO: gzip?
// don't serve templates
dir, name := filepath.Split(c.Vars["path"])
if dir == "" && strings.HasSuffix(name, ".html") {