Skip to content

Commit

Permalink
refact: move gzip to seperate file
Browse files Browse the repository at this point in the history
  • Loading branch information
taybart committed Jul 15, 2022
1 parent 5b0ba90 commit ca82862
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 25 deletions.
30 changes: 30 additions & 0 deletions server/gzip_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package server

import (
"compress/gzip"
"io"
"net/http"
"strings"
)

type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}

func (w gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func gzipHandler(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
fn(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
gzr := gzipResponseWriter{Writer: gz, ResponseWriter: w}
fn(gzr, r)
}
}
25 changes: 0 additions & 25 deletions server/server.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
package server

import (
"compress/gzip"
"fmt"
"io"
"net/http"
"net/http/httputil"
"os"
"path/filepath"
"strings"
"time"

"github.com/taybart/log"
Expand All @@ -18,28 +15,6 @@ const (
httpTimeout = 15 * time.Second
)

type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}

func (w gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func gzipHandler(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
fn(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
gzr := gzipResponseWriter{Writer: gz, ResponseWriter: w}
fn(gzr, r)
}
}

type Server struct {
router *http.ServeMux
c Config
Expand Down

0 comments on commit ca82862

Please sign in to comment.