forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gzip.go
68 lines (53 loc) · 1.18 KB
/
gzip.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Package gzip is a micro plugin for gzipping http response
package gzip
import (
"compress/gzip"
"io"
"net/http"
"strings"
"github.com/micro/cli"
"github.com/micro/micro/plugin"
)
type gzipWriter struct {
io.Writer
http.ResponseWriter
}
type gzipper struct{}
func (g *gzipper) Flags() []cli.Flag {
return nil
}
func (g *gzipper) Commands() []cli.Command {
return nil
}
func (g *gzipper) Handler() plugin.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// has gzip accept-encoding?
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
h.ServeHTTP(w, r)
return
}
// set the content-encoding
w.Header().Set("Content-Encoding", "gzip")
// create gzip writer
gz := gzip.NewWriter(w)
defer gz.Close()
// create http response writer
gzw := gzipWriter{gz, w}
// serve the request
h.ServeHTTP(gzw, r)
})
}
}
func (g *gzipper) Init(ctx *cli.Context) error {
return nil
}
func (g *gzipper) String() string {
return "gzip"
}
func (w gzipWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func New() plugin.Plugin {
return new(gzipper)
}