1
0

staticfile.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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/astaxie/beego/context"
  27. "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, 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, sch)
  82. return
  83. }
  84. type serveContentHolder struct {
  85. *bytes.Reader
  86. modTime time.Time
  87. size int64
  88. encoding string
  89. }
  90. var (
  91. staticFileMap = make(map[string]*serveContentHolder)
  92. mapLock sync.RWMutex
  93. )
  94. func openFile(filePath string, fi os.FileInfo, acceptEncoding string) (bool, string, *serveContentHolder, error) {
  95. mapKey := acceptEncoding + ":" + filePath
  96. mapLock.RLock()
  97. mapFile, _ := staticFileMap[mapKey]
  98. mapLock.RUnlock()
  99. if isOk(mapFile, fi) {
  100. return mapFile.encoding != "", mapFile.encoding, mapFile, nil
  101. }
  102. mapLock.Lock()
  103. defer mapLock.Unlock()
  104. if mapFile, _ = staticFileMap[mapKey]; !isOk(mapFile, fi) {
  105. file, err := os.Open(filePath)
  106. if err != nil {
  107. return false, "", nil, err
  108. }
  109. defer file.Close()
  110. var bufferWriter bytes.Buffer
  111. _, n, err := context.WriteFile(acceptEncoding, &bufferWriter, file)
  112. if err != nil {
  113. return false, "", nil, err
  114. }
  115. mapFile = &serveContentHolder{Reader: bytes.NewReader(bufferWriter.Bytes()), modTime: fi.ModTime(), size: int64(bufferWriter.Len()), encoding: n}
  116. staticFileMap[mapKey] = mapFile
  117. }
  118. return mapFile.encoding != "", mapFile.encoding, mapFile, nil
  119. }
  120. func isOk(s *serveContentHolder, fi os.FileInfo) bool {
  121. if s == nil {
  122. return false
  123. }
  124. return s.modTime == fi.ModTime() && s.size == fi.Size()
  125. }
  126. // isStaticCompress detect static files
  127. func isStaticCompress(filePath string) bool {
  128. for _, statExtension := range BConfig.WebConfig.StaticExtensionsToGzip {
  129. if strings.HasSuffix(strings.ToLower(filePath), strings.ToLower(statExtension)) {
  130. return true
  131. }
  132. }
  133. return false
  134. }
  135. // searchFile search the file by url path
  136. // if none the static file prefix matches ,return notStaticRequestErr
  137. func searchFile(ctx *context.Context) (string, os.FileInfo, error) {
  138. requestPath := filepath.ToSlash(filepath.Clean(ctx.Request.URL.Path))
  139. // special processing : favicon.ico/robots.txt can be in any static dir
  140. if requestPath == "/favicon.ico" || requestPath == "/robots.txt" {
  141. file := path.Join(".", requestPath)
  142. if fi, _ := os.Stat(file); fi != nil {
  143. return file, fi, nil
  144. }
  145. for _, staticDir := range BConfig.WebConfig.StaticDir {
  146. filePath := path.Join(staticDir, requestPath)
  147. if fi, _ := os.Stat(filePath); fi != nil {
  148. return filePath, fi, nil
  149. }
  150. }
  151. return "", nil, errNotStaticRequest
  152. }
  153. for prefix, staticDir := range BConfig.WebConfig.StaticDir {
  154. if !strings.Contains(requestPath, prefix) {
  155. continue
  156. }
  157. if len(requestPath) > len(prefix) && requestPath[len(prefix)] != '/' {
  158. continue
  159. }
  160. filePath := path.Join(staticDir, requestPath[len(prefix):])
  161. if fi, err := os.Stat(filePath); fi != nil {
  162. return filePath, fi, err
  163. }
  164. }
  165. return "", nil, errNotStaticRequest
  166. }
  167. // lookupFile find the file to serve
  168. // if the file is dir ,search the index.html as default file( MUST NOT A DIR also)
  169. // if the index.html not exist or is a dir, give a forbidden response depending on DirectoryIndex
  170. func lookupFile(ctx *context.Context) (bool, string, os.FileInfo, error) {
  171. fp, fi, err := searchFile(ctx)
  172. if fp == "" || fi == nil {
  173. return false, "", nil, err
  174. }
  175. if !fi.IsDir() {
  176. return false, fp, fi, err
  177. }
  178. if requestURL := ctx.Input.URL(); requestURL[len(requestURL)-1] == '/' {
  179. ifp := filepath.Join(fp, "index.html")
  180. if ifi, _ := os.Stat(ifp); ifi != nil && ifi.Mode().IsRegular() {
  181. return false, ifp, ifi, err
  182. }
  183. }
  184. return !BConfig.WebConfig.DirectoryIndex, fp, fi, err
  185. }