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

static.go 6.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. // Copyright 2013 Martini Authors
  2. // Copyright 2014 The Macaron Authors
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  5. // not use this file except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. package macaron
  16. import (
  17. "encoding/base64"
  18. "log"
  19. "net/http"
  20. "path"
  21. "path/filepath"
  22. "strings"
  23. "sync"
  24. )
  25. // StaticOptions is a struct for specifying configuration options for the macaron.Static middleware.
  26. type StaticOptions struct {
  27. // Prefix is the optional prefix used to serve the static directory content
  28. Prefix string
  29. // SkipLogging will disable [Static] log messages when a static file is served.
  30. SkipLogging bool
  31. // IndexFile defines which file to serve as index if it exists.
  32. IndexFile string
  33. // Expires defines which user-defined function to use for producing a HTTP Expires Header
  34. // https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
  35. Expires func() string
  36. // ETag defines if we should add an ETag header
  37. // https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching#validating-cached-responses-with-etags
  38. ETag bool
  39. // FileSystem is the interface for supporting any implmentation of file system.
  40. FileSystem http.FileSystem
  41. }
  42. // FIXME: to be deleted.
  43. type staticMap struct {
  44. lock sync.RWMutex
  45. data map[string]*http.Dir
  46. }
  47. func (sm *staticMap) Set(dir *http.Dir) {
  48. sm.lock.Lock()
  49. defer sm.lock.Unlock()
  50. sm.data[string(*dir)] = dir
  51. }
  52. func (sm *staticMap) Get(name string) *http.Dir {
  53. sm.lock.RLock()
  54. defer sm.lock.RUnlock()
  55. return sm.data[name]
  56. }
  57. func (sm *staticMap) Delete(name string) {
  58. sm.lock.Lock()
  59. defer sm.lock.Unlock()
  60. delete(sm.data, name)
  61. }
  62. var statics = staticMap{sync.RWMutex{}, map[string]*http.Dir{}}
  63. // staticFileSystem implements http.FileSystem interface.
  64. type staticFileSystem struct {
  65. dir *http.Dir
  66. }
  67. func newStaticFileSystem(directory string) staticFileSystem {
  68. if !filepath.IsAbs(directory) {
  69. directory = filepath.Join(Root, directory)
  70. }
  71. dir := http.Dir(directory)
  72. statics.Set(&dir)
  73. return staticFileSystem{&dir}
  74. }
  75. func (fs staticFileSystem) Open(name string) (http.File, error) {
  76. return fs.dir.Open(name)
  77. }
  78. func prepareStaticOption(dir string, opt StaticOptions) StaticOptions {
  79. // Defaults
  80. if len(opt.IndexFile) == 0 {
  81. opt.IndexFile = "index.html"
  82. }
  83. // Normalize the prefix if provided
  84. if opt.Prefix != "" {
  85. // Ensure we have a leading '/'
  86. if opt.Prefix[0] != '/' {
  87. opt.Prefix = "/" + opt.Prefix
  88. }
  89. // Remove any trailing '/'
  90. opt.Prefix = strings.TrimRight(opt.Prefix, "/")
  91. }
  92. if opt.FileSystem == nil {
  93. opt.FileSystem = newStaticFileSystem(dir)
  94. }
  95. return opt
  96. }
  97. func prepareStaticOptions(dir string, options []StaticOptions) StaticOptions {
  98. var opt StaticOptions
  99. if len(options) > 0 {
  100. opt = options[0]
  101. }
  102. return prepareStaticOption(dir, opt)
  103. }
  104. func staticHandler(ctx *Context, log *log.Logger, opt StaticOptions) bool {
  105. if ctx.Req.Method != "GET" && ctx.Req.Method != "HEAD" {
  106. return false
  107. }
  108. file := ctx.Req.URL.Path
  109. // if we have a prefix, filter requests by stripping the prefix
  110. if opt.Prefix != "" {
  111. if !strings.HasPrefix(file, opt.Prefix) {
  112. return false
  113. }
  114. file = file[len(opt.Prefix):]
  115. if file != "" && file[0] != '/' {
  116. return false
  117. }
  118. }
  119. f, err := opt.FileSystem.Open(file)
  120. if err != nil {
  121. return false
  122. }
  123. defer f.Close()
  124. fi, err := f.Stat()
  125. if err != nil {
  126. return true // File exists but fail to open.
  127. }
  128. // Try to serve index file
  129. if fi.IsDir() {
  130. redirPath := path.Clean(ctx.Req.URL.Path)
  131. // path.Clean removes the trailing slash, so we need to add it back when
  132. // the original path has it.
  133. if strings.HasSuffix(ctx.Req.URL.Path, "/") {
  134. redirPath = redirPath + "/"
  135. }
  136. // Redirect if missing trailing slash.
  137. if !strings.HasSuffix(redirPath, "/") {
  138. http.Redirect(ctx.Resp, ctx.Req.Request, redirPath+"/", http.StatusFound)
  139. return true
  140. }
  141. file = path.Join(file, opt.IndexFile)
  142. f, err = opt.FileSystem.Open(file)
  143. if err != nil {
  144. return false // Discard error.
  145. }
  146. defer f.Close()
  147. fi, err = f.Stat()
  148. if err != nil || fi.IsDir() {
  149. return true
  150. }
  151. }
  152. if !opt.SkipLogging {
  153. log.Println("[Static] Serving " + file)
  154. }
  155. // Add an Expires header to the static content
  156. if opt.Expires != nil {
  157. ctx.Resp.Header().Set("Expires", opt.Expires())
  158. }
  159. if opt.ETag {
  160. tag := `"` + GenerateETag(string(fi.Size()), fi.Name(), fi.ModTime().UTC().Format(http.TimeFormat)) + `"`
  161. ctx.Resp.Header().Set("ETag", tag)
  162. if ctx.Req.Header.Get("If-None-Match") == tag {
  163. ctx.Resp.WriteHeader(http.StatusNotModified)
  164. return true
  165. }
  166. }
  167. http.ServeContent(ctx.Resp, ctx.Req.Request, file, fi.ModTime(), f)
  168. return true
  169. }
  170. // GenerateETag generates an ETag based on size, filename and file modification time
  171. func GenerateETag(fileSize, fileName, modTime string) string {
  172. etag := fileSize + fileName + modTime
  173. return base64.StdEncoding.EncodeToString([]byte(etag))
  174. }
  175. // Static returns a middleware handler that serves static files in the given directory.
  176. func Static(directory string, staticOpt ...StaticOptions) Handler {
  177. opt := prepareStaticOptions(directory, staticOpt)
  178. return func(ctx *Context, log *log.Logger) {
  179. staticHandler(ctx, log, opt)
  180. }
  181. }
  182. // Statics registers multiple static middleware handlers all at once.
  183. func Statics(opt StaticOptions, dirs ...string) Handler {
  184. if len(dirs) == 0 {
  185. panic("no static directory is given")
  186. }
  187. opts := make([]StaticOptions, len(dirs))
  188. for i := range dirs {
  189. opts[i] = prepareStaticOption(dirs[i], opt)
  190. }
  191. return func(ctx *Context, log *log.Logger) {
  192. for i := range opts {
  193. if staticHandler(ctx, log, opts[i]) {
  194. return
  195. }
  196. }
  197. }
  198. }