1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-23 00:20:55 +00:00
Beego/context/acceptencoder.go

233 lines
6.7 KiB
Go
Raw Normal View History

2015-11-11 05:47:36 +00:00
// Copyright 2015 beego Author. All Rights Reserved.
//
// 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 context
import (
2015-11-12 03:44:29 +00:00
"bytes"
2015-11-11 05:47:36 +00:00
"compress/flate"
"compress/gzip"
2015-12-18 01:28:40 +00:00
"compress/zlib"
2015-11-11 05:47:36 +00:00
"io"
"net/http"
"os"
"strconv"
"strings"
"sync"
2016-03-17 11:09:21 +00:00
)
var (
2016-03-17 12:07:24 +00:00
//Default size==20B same as nginx
2016-03-17 11:40:29 +00:00
defaultGzipMinLength = 20
//Content will only be compressed if content length is either unknown or greater than gzipMinLength.
gzipMinLength = defaultGzipMinLength
2016-03-17 11:40:29 +00:00
//The compression level used for deflate compression. (0-9).
2016-03-17 11:09:21 +00:00
gzipCompressLevel int
2016-03-17 11:40:29 +00:00
//List of HTTP methods to compress. If not set, only GET requests are compressed.
2016-03-17 11:09:21 +00:00
includedMethods map[string]bool
getMethodOnly bool
2015-11-11 05:47:36 +00:00
)
2017-04-30 14:41:23 +00:00
// InitGzip init the gzipcompress
func InitGzip(minLength, compressLevel int, methods []string) {
if minLength >= 0 {
gzipMinLength = minLength
}
gzipCompressLevel = compressLevel
2016-03-22 08:47:11 +00:00
if gzipCompressLevel < flate.NoCompression || gzipCompressLevel > flate.BestCompression {
2016-03-17 11:09:21 +00:00
gzipCompressLevel = flate.BestSpeed
}
2016-03-18 07:18:00 +00:00
getMethodOnly = (len(methods) == 0) || (len(methods) == 1 && strings.ToUpper(methods[0]) == "GET")
2016-03-21 01:32:41 +00:00
includedMethods = make(map[string]bool, len(methods))
2016-03-17 11:09:21 +00:00
for _, v := range methods {
includedMethods[strings.ToUpper(v)] = true
}
}
type resetWriter interface {
io.Writer
Reset(w io.Writer)
}
type nopResetWriter struct {
io.Writer
}
func (n nopResetWriter) Reset(w io.Writer) {
//do nothing
}
type acceptEncoder struct {
2016-03-17 11:09:21 +00:00
name string
levelEncode func(int) resetWriter
customCompressLevelPool *sync.Pool
bestCompressionPool *sync.Pool
}
2016-01-04 00:50:59 +00:00
func (ac acceptEncoder) encode(wr io.Writer, level int) resetWriter {
2016-03-17 11:09:21 +00:00
if ac.customCompressLevelPool == nil || ac.bestCompressionPool == nil {
2016-01-04 00:50:59 +00:00
return nopResetWriter{wr}
}
var rwr resetWriter
2016-01-03 07:35:32 +00:00
switch level {
case flate.BestSpeed:
2016-03-17 11:09:21 +00:00
rwr = ac.customCompressLevelPool.Get().(resetWriter)
2016-01-03 07:35:32 +00:00
case flate.BestCompression:
rwr = ac.bestCompressionPool.Get().(resetWriter)
2016-01-03 07:35:32 +00:00
default:
rwr = ac.levelEncode(level)
}
rwr.Reset(wr)
2016-01-04 00:50:59 +00:00
return rwr
}
func (ac acceptEncoder) put(wr resetWriter, level int) {
2016-03-17 11:09:21 +00:00
if ac.customCompressLevelPool == nil || ac.bestCompressionPool == nil {
return
}
wr.Reset(nil)
2016-03-17 11:40:29 +00:00
2016-03-17 11:09:21 +00:00
//notice
//compressionLevel==BestCompression DOES NOT MATTER
//sync.Pool will not memory leak
2016-03-17 11:40:29 +00:00
switch level {
2016-03-17 11:09:21 +00:00
case gzipCompressLevel:
ac.customCompressLevelPool.Put(wr)
case flate.BestCompression:
ac.bestCompressionPool.Put(wr)
}
}
var (
2016-01-03 07:35:32 +00:00
noneCompressEncoder = acceptEncoder{"", nil, nil, nil}
2016-03-17 11:09:21 +00:00
gzipCompressEncoder = acceptEncoder{
name: "gzip",
levelEncode: func(level int) resetWriter { wr, _ := gzip.NewWriterLevel(nil, level); return wr },
customCompressLevelPool: &sync.Pool{New: func() interface{} { wr, _ := gzip.NewWriterLevel(nil, gzipCompressLevel); return wr }},
bestCompressionPool: &sync.Pool{New: func() interface{} { wr, _ := gzip.NewWriterLevel(nil, flate.BestCompression); return wr }},
}
2016-03-17 11:40:29 +00:00
//according to the sec :http://tools.ietf.org/html/rfc2616#section-3.5 ,the deflate compress in http is zlib indeed
//deflate
//The "zlib" format defined in RFC 1950 [31] in combination with
//the "deflate" compression mechanism described in RFC 1951 [29].
2016-03-17 11:09:21 +00:00
deflateCompressEncoder = acceptEncoder{
name: "deflate",
levelEncode: func(level int) resetWriter { wr, _ := zlib.NewWriterLevel(nil, level); return wr },
customCompressLevelPool: &sync.Pool{New: func() interface{} { wr, _ := zlib.NewWriterLevel(nil, gzipCompressLevel); return wr }},
bestCompressionPool: &sync.Pool{New: func() interface{} { wr, _ := zlib.NewWriterLevel(nil, flate.BestCompression); return wr }},
}
)
var (
encoderMap = map[string]acceptEncoder{ // all the other compress methods will ignore
"gzip": gzipCompressEncoder,
"deflate": deflateCompressEncoder,
"*": gzipCompressEncoder, // * means any compress will accept,we prefer gzip
"identity": noneCompressEncoder, // identity means none-compress
}
)
2015-11-11 05:47:36 +00:00
// WriteFile reads from file and writes to writer by the specific encoding(gzip/deflate)
func WriteFile(encoding string, writer io.Writer, file *os.File) (bool, string, error) {
2015-11-12 03:44:29 +00:00
return writeLevel(encoding, writer, file, flate.BestCompression)
2015-11-11 05:47:36 +00:00
}
// WriteBody reads writes content to writer by the specific encoding(gzip/deflate)
func WriteBody(encoding string, writer io.Writer, content []byte) (bool, string, error) {
2016-03-17 11:09:21 +00:00
if encoding == "" || len(content) < gzipMinLength {
_, err := writer.Write(content)
return false, "", err
}
return writeLevel(encoding, writer, bytes.NewReader(content), gzipCompressLevel)
2015-11-11 05:47:36 +00:00
}
// writeLevel reads from reader,writes to writer by specific encoding and compress level
// the compress level is defined by deflate package
2015-11-12 03:44:29 +00:00
func writeLevel(encoding string, writer io.Writer, reader io.Reader, level int) (bool, string, error) {
var outputWriter resetWriter
2015-11-11 05:47:36 +00:00
var err error
var ce = noneCompressEncoder
2015-11-11 05:47:36 +00:00
if cf, ok := encoderMap[encoding]; ok {
ce = cf
2015-11-11 05:47:36 +00:00
}
encoding = ce.name
2016-01-04 00:50:59 +00:00
outputWriter = ce.encode(writer, level)
defer ce.put(outputWriter, level)
_, err = io.Copy(outputWriter, reader)
if err != nil {
return false, "", err
}
2015-11-11 05:47:36 +00:00
switch outputWriter.(type) {
case io.WriteCloser:
outputWriter.(io.WriteCloser).Close()
}
return encoding != "", encoding, nil
}
// ParseEncoding will extract the right encoding for response
// the Accept-Encoding's sec is here:
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
func ParseEncoding(r *http.Request) string {
if r == nil {
return ""
}
2016-03-17 11:09:21 +00:00
if (getMethodOnly && r.Method == "GET") || includedMethods[r.Method] {
return parseEncoding(r)
}
return ""
2015-11-11 05:47:36 +00:00
}
type q struct {
name string
value float64
}
func parseEncoding(r *http.Request) string {
acceptEncoding := r.Header.Get("Accept-Encoding")
if acceptEncoding == "" {
return ""
}
var lastQ q
for _, v := range strings.Split(acceptEncoding, ",") {
v = strings.TrimSpace(v)
if v == "" {
continue
}
vs := strings.Split(v, ";")
2016-07-27 01:31:53 +00:00
var cf acceptEncoder
var ok bool
if cf, ok = encoderMap[vs[0]]; !ok {
continue
}
2015-11-11 05:47:36 +00:00
if len(vs) == 1 {
2016-07-27 01:31:53 +00:00
return cf.name
2015-11-11 05:47:36 +00:00
}
if len(vs) == 2 {
f, _ := strconv.ParseFloat(strings.Replace(vs[1], "q=", "", -1), 64)
if f == 0 {
continue
}
if f > lastQ.value {
2016-07-27 01:31:53 +00:00
lastQ = q{cf.name, f}
2015-11-11 05:47:36 +00:00
}
}
}
2016-07-27 01:31:53 +00:00
return lastQ.name
2015-11-11 05:47:36 +00:00
}