static.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. // Redirect if missing trailing slash.
  131. if !strings.HasSuffix(ctx.Req.URL.Path, "/") {
  132. http.Redirect(ctx.Resp, ctx.Req.Request, ctx.Req.URL.Path+"/", http.StatusFound)
  133. return true
  134. }
  135. file = path.Join(file, opt.IndexFile)
  136. f, err = opt.FileSystem.Open(file)
  137. if err != nil {
  138. return false // Discard error.
  139. }
  140. defer f.Close()
  141. fi, err = f.Stat()
  142. if err != nil || fi.IsDir() {
  143. return true
  144. }
  145. }
  146. if !opt.SkipLogging {
  147. log.Println("[Static] Serving " + file)
  148. }
  149. // Add an Expires header to the static content
  150. if opt.Expires != nil {
  151. ctx.Resp.Header().Set("Expires", opt.Expires())
  152. }
  153. if opt.ETag {
  154. tag := GenerateETag(string(fi.Size()), fi.Name(), fi.ModTime().UTC().Format(http.TimeFormat))
  155. ctx.Resp.Header().Set("ETag", tag)
  156. }
  157. http.ServeContent(ctx.Resp, ctx.Req.Request, file, fi.ModTime(), f)
  158. return true
  159. }
  160. // GenerateETag generates an ETag based on size, filename and file modification time
  161. func GenerateETag(fileSize, fileName, modTime string) string {
  162. etag := fileSize + fileName + modTime
  163. return base64.StdEncoding.EncodeToString([]byte(etag))
  164. }
  165. // Static returns a middleware handler that serves static files in the given directory.
  166. func Static(directory string, staticOpt ...StaticOptions) Handler {
  167. opt := prepareStaticOptions(directory, staticOpt)
  168. return func(ctx *Context, log *log.Logger) {
  169. staticHandler(ctx, log, opt)
  170. }
  171. }
  172. // Statics registers multiple static middleware handlers all at once.
  173. func Statics(opt StaticOptions, dirs ...string) Handler {
  174. if len(dirs) == 0 {
  175. panic("no static directory is given")
  176. }
  177. opts := make([]StaticOptions, len(dirs))
  178. for i := range dirs {
  179. opts[i] = prepareStaticOption(dirs[i], opt)
  180. }
  181. return func(ctx *Context, log *log.Logger) {
  182. for i := range opts {
  183. if staticHandler(ctx, log, opts[i]) {
  184. return
  185. }
  186. }
  187. }
  188. }