You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

преди 9 години
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. /* ----------------------------------------------------------------------
  2. * ______ ___ __
  3. * / ____/___ / | ____ __ ___ __/ /_ ___ ________
  4. * / / __/ __ \/ /| | / __ \/ / / / | /| / / __ \/ _ \/ ___/ _ \
  5. * / /_/ / /_/ / ___ |/ / / / /_/ /| |/ |/ / / / / __/ / / __/
  6. * \____/\____/_/ |_/_/ /_/\__. / |__/|__/_/ /_/\___/_/ \___/
  7. * /____/
  8. *
  9. * (C) Copyright 2015 GoAnywhere (http://goanywhere.io).
  10. * ----------------------------------------------------------------------
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. * ----------------------------------------------------------------------*/
  23. package modules
  24. import (
  25. "bytes"
  26. "compress/flate"
  27. "compress/gzip"
  28. "io"
  29. "net/http"
  30. "regexp"
  31. "strings"
  32. )
  33. var (
  34. regexAcceptEncoding = regexp.MustCompile(`(gzip|deflate|\*)(;q=(1(\.0)?|0(\.[0-9])?))?`)
  35. regexContentType = regexp.MustCompile(`((message|text)\/.+)|((application\/).*(javascript|json|xml))`)
  36. )
  37. type compression interface {
  38. io.WriteCloser
  39. }
  40. type compressor struct {
  41. http.ResponseWriter
  42. encodings []string
  43. }
  44. // AcceptEncodings fetches the requested encodings from client with priority.
  45. func (self *compressor) acceptEncodings(request *http.Request) (encodings []string) {
  46. // find all encodings supported by backend server.
  47. matches := regexAcceptEncoding.FindAllString(request.Header.Get("Accept-Encoding"), -1)
  48. for _, item := range matches {
  49. units := strings.SplitN(item, ";", 2)
  50. // top priority with q=1|q=1.0|Not Specified.
  51. if len(units) == 1 {
  52. encodings = append(encodings, units[0])
  53. } else {
  54. if strings.HasPrefix(units[1], "q=1") {
  55. // insert the specified top priority to the first.
  56. encodings = append([]string{units[0]}, encodings...)
  57. } else if strings.HasSuffix(units[1], "0") {
  58. // not acceptable at client side.
  59. continue
  60. } else {
  61. // lower priority encoding
  62. encodings = append(encodings, units[0])
  63. }
  64. }
  65. }
  66. return
  67. }
  68. func (self *compressor) filter(src []byte) ([]byte, string) {
  69. var mimetype = self.Header().Get("Content-Type")
  70. if mimetype == "" {
  71. mimetype = http.DetectContentType(src)
  72. self.Header().Set("Content-Type", mimetype)
  73. }
  74. if self.Header().Get("Content-Encoding") != "" {
  75. return src, ""
  76. }
  77. if !regexContentType.MatchString(strings.TrimSpace(strings.SplitN(mimetype, ";", 2)[0])) {
  78. return src, ""
  79. }
  80. // okay to start compressing.
  81. var e error
  82. var encoding string
  83. var writer compression
  84. var buffer *bytes.Buffer = new(bytes.Buffer)
  85. // try compress the data, if any error occrued, fallback to ResponseWriter.
  86. if self.encodings[0] == "deflate" {
  87. encoding = "deflate"
  88. writer, e = flate.NewWriter(buffer, flate.DefaultCompression)
  89. } else {
  90. encoding = "gzip"
  91. writer, e = gzip.NewWriterLevel(buffer, gzip.DefaultCompression)
  92. }
  93. _, e = writer.Write(src)
  94. writer.Close()
  95. if e == nil {
  96. return buffer.Bytes(), encoding
  97. }
  98. // fallback to standard http.ResponseWriter, nothing happened~ (~__~"")
  99. return src, ""
  100. }
  101. func (self *compressor) Write(data []byte) (size int, err error) {
  102. if bytes, encoding := self.filter(data); encoding != "" {
  103. self.Header().Set("Content-Encoding", encoding)
  104. self.Header().Add("Vary", "Accept-Encoding")
  105. self.Header().Del("Content-Length")
  106. return self.ResponseWriter.Write(bytes)
  107. }
  108. return self.ResponseWriter.Write(data)
  109. }
  110. func Compress(next http.Handler) http.Handler {
  111. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  112. if r.Header.Get("Sec-WebSocket-Key") != "" || r.Method == "HEAD" {
  113. next.ServeHTTP(w, r)
  114. } else {
  115. compressor := new(compressor)
  116. compressor.ResponseWriter = w
  117. encodings := compressor.acceptEncodings(r)
  118. if len(encodings) == 0 {
  119. next.ServeHTTP(w, r)
  120. } else {
  121. compressor.encodings = encodings
  122. next.ServeHTTP(compressor, r)
  123. }
  124. }
  125. })
  126. }