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.

205 lines
5.0 KiB

  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. "log"
  18. "net/http"
  19. "path"
  20. "path/filepath"
  21. "strings"
  22. "sync"
  23. )
  24. // StaticOptions is a struct for specifying configuration options for the macaron.Static middleware.
  25. type StaticOptions struct {
  26. // Prefix is the optional prefix used to serve the static directory content
  27. Prefix string
  28. // SkipLogging will disable [Static] log messages when a static file is served.
  29. SkipLogging bool
  30. // IndexFile defines which file to serve as index if it exists.
  31. IndexFile string
  32. // Expires defines which user-defined function to use for producing a HTTP Expires Header
  33. // https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
  34. Expires func() string
  35. // FileSystem is the interface for supporting any implmentation of file system.
  36. FileSystem http.FileSystem
  37. }
  38. // FIXME: to be deleted.
  39. type staticMap struct {
  40. lock sync.RWMutex
  41. data map[string]*http.Dir
  42. }
  43. func (sm *staticMap) Set(dir *http.Dir) {
  44. sm.lock.Lock()
  45. defer sm.lock.Unlock()
  46. sm.data[string(*dir)] = dir
  47. }
  48. func (sm *staticMap) Get(name string) *http.Dir {
  49. sm.lock.RLock()
  50. defer sm.lock.RUnlock()
  51. return sm.data[name]
  52. }
  53. func (sm *staticMap) Delete(name string) {
  54. sm.lock.Lock()
  55. defer sm.lock.Unlock()
  56. delete(sm.data, name)
  57. }
  58. var statics = staticMap{sync.RWMutex{}, map[string]*http.Dir{}}
  59. // staticFileSystem implements http.FileSystem interface.
  60. type staticFileSystem struct {
  61. dir *http.Dir
  62. }
  63. func newStaticFileSystem(directory string) staticFileSystem {
  64. if !filepath.IsAbs(directory) {
  65. directory = filepath.Join(Root, directory)
  66. }
  67. dir := http.Dir(directory)
  68. statics.Set(&dir)
  69. return staticFileSystem{&dir}
  70. }
  71. func (fs staticFileSystem) Open(name string) (http.File, error) {
  72. return fs.dir.Open(name)
  73. }
  74. func prepareStaticOption(dir string, opt StaticOptions) StaticOptions {
  75. // Defaults
  76. if len(opt.IndexFile) == 0 {
  77. opt.IndexFile = "index.html"
  78. }
  79. // Normalize the prefix if provided
  80. if opt.Prefix != "" {
  81. // Ensure we have a leading '/'
  82. if opt.Prefix[0] != '/' {
  83. opt.Prefix = "/" + opt.Prefix
  84. }
  85. // Remove any trailing '/'
  86. opt.Prefix = strings.TrimRight(opt.Prefix, "/")
  87. }
  88. if opt.FileSystem == nil {
  89. opt.FileSystem = newStaticFileSystem(dir)
  90. }
  91. return opt
  92. }
  93. func prepareStaticOptions(dir string, options []StaticOptions) StaticOptions {
  94. var opt StaticOptions
  95. if len(options) > 0 {
  96. opt = options[0]
  97. }
  98. return prepareStaticOption(dir, opt)
  99. }
  100. func staticHandler(ctx *Context, log *log.Logger, opt StaticOptions) bool {
  101. if ctx.Req.Method != "GET" && ctx.Req.Method != "HEAD" {
  102. return false
  103. }
  104. file := ctx.Req.URL.Path
  105. // if we have a prefix, filter requests by stripping the prefix
  106. if opt.Prefix != "" {
  107. if !strings.HasPrefix(file, opt.Prefix) {
  108. return false
  109. }
  110. file = file[len(opt.Prefix):]
  111. if file != "" && file[0] != '/' {
  112. return false
  113. }
  114. }
  115. f, err := opt.FileSystem.Open(file)
  116. if err != nil {
  117. return false
  118. }
  119. defer f.Close()
  120. fi, err := f.Stat()
  121. if err != nil {
  122. return true // File exists but fail to open.
  123. }
  124. // Try to serve index file
  125. if fi.IsDir() {
  126. // Redirect if missing trailing slash.
  127. if !strings.HasSuffix(ctx.Req.URL.Path, "/") {
  128. http.Redirect(ctx.Resp, ctx.Req.Request, ctx.Req.URL.Path+"/", http.StatusFound)
  129. return true
  130. }
  131. file = path.Join(file, opt.IndexFile)
  132. f, err = opt.FileSystem.Open(file)
  133. if err != nil {
  134. return false // Discard error.
  135. }
  136. defer f.Close()
  137. fi, err = f.Stat()
  138. if err != nil || fi.IsDir() {
  139. return true
  140. }
  141. }
  142. if !opt.SkipLogging {
  143. log.Println("[Static] Serving " + file)
  144. }
  145. // Add an Expires header to the static content
  146. if opt.Expires != nil {
  147. ctx.Resp.Header().Set("Expires", opt.Expires())
  148. }
  149. http.ServeContent(ctx.Resp, ctx.Req.Request, file, fi.ModTime(), f)
  150. return true
  151. }
  152. // Static returns a middleware handler that serves static files in the given directory.
  153. func Static(directory string, staticOpt ...StaticOptions) Handler {
  154. opt := prepareStaticOptions(directory, staticOpt)
  155. return func(ctx *Context, log *log.Logger) {
  156. staticHandler(ctx, log, opt)
  157. }
  158. }
  159. // Statics registers multiple static middleware handlers all at once.
  160. func Statics(opt StaticOptions, dirs ...string) Handler {
  161. if len(dirs) == 0 {
  162. panic("no static directory is given")
  163. }
  164. opts := make([]StaticOptions, len(dirs))
  165. for i := range dirs {
  166. opts[i] = prepareStaticOption(dirs[i], opt)
  167. }
  168. return func(ctx *Context, log *log.Logger) {
  169. for i := range opts {
  170. if staticHandler(ctx, log, opts[i]) {
  171. return
  172. }
  173. }
  174. }
  175. }