summaryrefslogtreecommitdiff
path: root/service/gzip/service.go
blob: 5ae3ffd5ab28bdcded4371ab031d9f548a329533 (plain)
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
package gzip

import (
	"errors"
	"github.com/NYTimes/gziphandler"
	rrhttp "github.com/spiral/roadrunner/service/http"
	"net/http"
)

// ID contains default service name.
const ID = "gzip"
var httpNotInitialized = errors.New("http service should be defined properly in config")

type Service struct {
	cfg *Config
}

func (s *Service) Init(cfg *Config, r *rrhttp.Service) (bool, error) {
	if r == nil {
		return false, httpNotInitialized
	}
	s.cfg = cfg

	if !s.cfg.Enable {
		return false, nil
	}

	r.AddMiddleware(s.middleware)

	return true, nil
}

func (s *Service) middleware(f http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		gziphandler.GzipHandler(f).ServeHTTP(w, r)
	}
}