staticfile.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package beego
  15. import (
  16. "bytes"
  17. "errors"
  18. "net/http"
  19. "os"
  20. "path"
  21. "path/filepath"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "time"
  26. "github.com/cnlh/nps/vender/github.com/astaxie/beego/context"
  27. "github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
  28. )
  29. var errNotStaticRequest = errors.New("request not a static file request")
  30. func serverStaticRouter(ctx *context.Context) {
  31. if ctx.Input.Method() != "GET" && ctx.Input.Method() != "HEAD" {
  32. return
  33. }
  34. forbidden, filePath, fileInfo, err := lookupFile(ctx)
  35. if err == errNotStaticRequest {
  36. return
  37. }
  38. if forbidden {
  39. exception("403", ctx)
  40. return
  41. }
  42. if filePath == "" || fileInfo == nil {
  43. if BConfig.RunMode == DEV {
  44. logs.Warn("Can't find/open the file:", filePath, err)
  45. }
  46. http.NotFound(ctx.ResponseWriter, ctx.Request)
  47. return
  48. }
  49. if fileInfo.IsDir() {
  50. requestURL := ctx.Input.URL()
  51. if requestURL[len(requestURL)-1] != '/' {
  52. redirectURL := requestURL + "/"
  53. if ctx.Request.URL.RawQuery != "" {
  54. redirectURL = redirectURL + "?" + ctx.Request.URL.RawQuery
  55. }
  56. ctx.Redirect(302, redirectURL)
  57. } else {
  58. //serveFile will list dir
  59. http.ServeFile(ctx.ResponseWriter, ctx.Request, filePath)
  60. }
  61. return
  62. }
  63. var enableCompress = BConfig.EnableGzip && isStaticCompress(filePath)
  64. var acceptEncoding string
  65. if enableCompress {
  66. acceptEncoding = context.ParseEncoding(ctx.Request)
  67. }
  68. b, n, sch, reader, err := openFile(filePath, fileInfo, acceptEncoding)
  69. if err != nil {
  70. if BConfig.RunMode == DEV {
  71. logs.Warn("Can't compress the file:", filePath, err)
  72. }
  73. http.NotFound(ctx.ResponseWriter, ctx.Request)
  74. return
  75. }
  76. if b {
  77. ctx.Output.Header("Content-Encoding", n)
  78. } else {
  79. ctx.Output.Header("Content-Length", strconv.FormatInt(sch.size, 10))
  80. }
  81. http.ServeContent(ctx.ResponseWriter, ctx.Request, filePath, sch.modTime, reader)
  82. }
  83. type serveContentHolder struct {
  84. data []byte
  85. modTime time.Time
  86. size int64
  87. encoding string
  88. }
  89. type serveContentReader struct {
  90. *bytes.Reader
  91. }
  92. var (
  93. staticFileMap = make(map[string]*serveContentHolder)
  94. mapLock sync.RWMutex
  95. )
  96. func openFile(filePath string, fi os.FileInfo, acceptEncoding string) (bool, string, *serveContentHolder, *serveContentReader, error) {
  97. mapKey := acceptEncoding + ":" + filePath
  98. mapLock.RLock()
  99. mapFile := staticFileMap[mapKey]
  100. mapLock.RUnlock()
  101. if isOk(mapFile, fi) {
  102. reader := &serveContentReader{Reader: bytes.NewReader(mapFile.data)}
  103. return mapFile.encoding != "", mapFile.encoding, mapFile, reader, nil
  104. }
  105. mapLock.Lock()
  106. defer mapLock.Unlock()
  107. if mapFile = staticFileMap[mapKey]; !isOk(mapFile, fi) {
  108. file, err := os.Open(filePath)
  109. if err != nil {
  110. return false, "", nil, nil, err
  111. }
  112. defer file.Close()
  113. var bufferWriter bytes.Buffer
  114. _, n, err := context.WriteFile(acceptEncoding, &bufferWriter, file)
  115. if err != nil {
  116. return false, "", nil, nil, err
  117. }
  118. mapFile = &serveContentHolder{data: bufferWriter.Bytes(), modTime: fi.ModTime(), size: int64(bufferWriter.Len()), encoding: n}
  119. staticFileMap[mapKey] = mapFile
  120. }
  121. reader := &serveContentReader{Reader: bytes.NewReader(mapFile.data)}
  122. return mapFile.encoding != "", mapFile.encoding, mapFile, reader, nil
  123. }
  124. func isOk(s *serveContentHolder, fi os.FileInfo) bool {
  125. if s == nil {
  126. return false
  127. }
  128. return s.modTime == fi.ModTime() && s.size == fi.Size()
  129. }
  130. // isStaticCompress detect static files
  131. func isStaticCompress(filePath string) bool {
  132. for _, statExtension := range BConfig.WebConfig.StaticExtensionsToGzip {
  133. if strings.HasSuffix(strings.ToLower(filePath), strings.ToLower(statExtension)) {
  134. return true
  135. }
  136. }
  137. return false
  138. }
  139. // searchFile search the file by url path
  140. // if none the static file prefix matches ,return notStaticRequestErr
  141. func searchFile(ctx *context.Context) (string, os.FileInfo, error) {
  142. requestPath := filepath.ToSlash(filepath.Clean(ctx.Request.URL.Path))
  143. // special processing : favicon.ico/robots.txt can be in any static dir
  144. if requestPath == "/favicon.ico" || requestPath == "/robots.txt" {
  145. file := path.Join(".", requestPath)
  146. if fi, _ := os.Stat(file); fi != nil {
  147. return file, fi, nil
  148. }
  149. for _, staticDir := range BConfig.WebConfig.StaticDir {
  150. filePath := path.Join(staticDir, requestPath)
  151. if fi, _ := os.Stat(filePath); fi != nil {
  152. return filePath, fi, nil
  153. }
  154. }
  155. return "", nil, errNotStaticRequest
  156. }
  157. for prefix, staticDir := range BConfig.WebConfig.StaticDir {
  158. if !strings.Contains(requestPath, prefix) {
  159. continue
  160. }
  161. if prefix != "/" && len(requestPath) > len(prefix) && requestPath[len(prefix)] != '/' {
  162. continue
  163. }
  164. filePath := path.Join(staticDir, requestPath[len(prefix):])
  165. if fi, err := os.Stat(filePath); fi != nil {
  166. return filePath, fi, err
  167. }
  168. }
  169. return "", nil, errNotStaticRequest
  170. }
  171. // lookupFile find the file to serve
  172. // if the file is dir ,search the index.html as default file( MUST NOT A DIR also)
  173. // if the index.html not exist or is a dir, give a forbidden response depending on DirectoryIndex
  174. func lookupFile(ctx *context.Context) (bool, string, os.FileInfo, error) {
  175. fp, fi, err := searchFile(ctx)
  176. if fp == "" || fi == nil {
  177. return false, "", nil, err
  178. }
  179. if !fi.IsDir() {
  180. return false, fp, fi, err
  181. }
  182. if requestURL := ctx.Input.URL(); requestURL[len(requestURL)-1] == '/' {
  183. ifp := filepath.Join(fp, "index.html")
  184. if ifi, _ := os.Stat(ifp); ifi != nil && ifi.Mode().IsRegular() {
  185. return false, ifp, ifi, err
  186. }
  187. }
  188. return !BConfig.WebConfig.DirectoryIndex, fp, fi, err
  189. }