Skip to content

Commit

Permalink
[core] implement http.Pusher on our composite gzip/response writer (#45)
Browse files Browse the repository at this point in the history
  • Loading branch information
nilslice authored Jan 25, 2017
1 parent 2a979e8 commit 3dea30f
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions system/api/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ func contentHandler(res http.ResponseWriter, req *http.Request) {
return
}

defer push(res, req, pt, post)
push(res, req, pt, post)

j, err := fmtJSON(json.RawMessage(post))
if err != nil {
Expand Down Expand Up @@ -166,7 +166,7 @@ func contentHandlerBySlug(res http.ResponseWriter, req *http.Request) {
return
}

defer push(res, req, it, post)
push(res, req, it, post)

j, err := fmtJSON(json.RawMessage(post))
if err != nil {
Expand Down Expand Up @@ -332,7 +332,12 @@ func Gzip(next http.HandlerFunc) http.HandlerFunc {
if strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") {
// gzip response data
res.Header().Set("Content-Encoding", "gzip")
gzres := gzipResponseWriter{res, gzip.NewWriter(res)}
var gzres gzipResponseWriter
if pusher, ok := res.(http.Pusher); ok {
gzres = gzipResponseWriter{res, pusher, gzip.NewWriter(res)}
} else {
gzres = gzipResponseWriter{res, nil, gzip.NewWriter(res)}
}

next.ServeHTTP(gzres, req)
return
Expand All @@ -344,10 +349,24 @@ func Gzip(next http.HandlerFunc) http.HandlerFunc {

type gzipResponseWriter struct {
http.ResponseWriter
pusher http.Pusher

gw *gzip.Writer
}

func (gzw gzipResponseWriter) Write(p []byte) (int, error) {
defer gzw.gw.Close()
return gzw.gw.Write(p)
}

func (gzw gzipResponseWriter) Push(target string, opts *http.PushOptions) error {
if opts == nil {
opts = &http.PushOptions{
Header: make(http.Header),
}
}

opts.Header.Set("Accept-Encoding", "gzip")

return gzw.pusher.Push(target, opts)
}

0 comments on commit 3dea30f

Please sign in to comment.