/
GZip.scala
85 lines (77 loc) · 2.83 KB
/
GZip.scala
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* Copyright 2014 http4s.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.http4s
package server
package middleware
import cats.Functor
import cats.data.Kleisli
import cats.effect.Sync
import cats.syntax.all._
import fs2.compression._
import java.util.zip.Deflater
import org.http4s.headers._
import org.log4s.getLogger
object GZip {
private[this] val logger = getLogger
// TODO: It could be possible to look for F.pure type bodies, and change the Content-Length header after
// TODO zipping and buffering all the input. Just a thought.
def apply[F[_]: Functor, G[_]: Sync](
http: Http[F, G],
bufferSize: Int = 32 * 1024,
level: Int = Deflater.DEFAULT_COMPRESSION,
isZippable: Response[G] => Boolean = defaultIsZippable[G](_: Response[G])
): Http[F, G] =
Kleisli { (req: Request[G]) =>
req.headers.get[`Accept-Encoding`] match {
case Some(acceptEncoding) if satisfiedByGzip(acceptEncoding) =>
http(req).map(zipOrPass(_, bufferSize, level, isZippable))
case _ => http(req)
}
}
def defaultIsZippable[F[_]](resp: Response[F]): Boolean = {
val contentType = resp.headers.get[`Content-Type`]
resp.headers.get[`Content-Encoding`].isEmpty &&
resp.status.isEntityAllowed &&
(contentType.isEmpty || contentType.get.mediaType.compressible ||
(contentType.get.mediaType eq MediaType.application.`octet-stream`))
}
private def satisfiedByGzip(acceptEncoding: `Accept-Encoding`) =
acceptEncoding.satisfiedBy(ContentCoding.gzip) || acceptEncoding.satisfiedBy(
ContentCoding.`x-gzip`)
private def zipOrPass[F[_]: Sync](
response: Response[F],
bufferSize: Int,
level: Int,
isZippable: Response[F] => Boolean): Response[F] =
response match {
case resp if isZippable(resp) => zipResponse(bufferSize, level, resp)
case resp => resp // Don't touch it, Content-Encoding already set
}
private def zipResponse[F[_]: Sync](
bufferSize: Int,
level: Int,
resp: Response[F]): Response[F] = {
logger.trace("GZip middleware encoding content")
resp
.removeHeader[`Content-Length`]
.putHeaders(`Content-Encoding`(ContentCoding.gzip))
.copy(body = resp.body.through(
gzip(
bufferSize = bufferSize,
deflateLevel = Some(level)
)))
}
}