static.go 5.2 KB

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