static.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. package martini
  2. import (
  3. "log"
  4. "net/http"
  5. "net/url"
  6. "path"
  7. "path/filepath"
  8. "strings"
  9. )
  10. // StaticOptions is a struct for specifying configuration options for the martini.Static middleware.
  11. type StaticOptions struct {
  12. // Prefix is the optional prefix used to serve the static directory content
  13. Prefix string
  14. // SkipLogging will disable [Static] log messages when a static file is served.
  15. SkipLogging bool
  16. // IndexFile defines which file to serve as index if it exists.
  17. IndexFile string
  18. // Expires defines which user-defined function to use for producing a HTTP Expires Header
  19. // https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
  20. Expires func() string
  21. // Fallback defines a default URL to serve when the requested resource was
  22. // not found.
  23. Fallback string
  24. // Exclude defines a pattern for URLs this handler should never process.
  25. Exclude string
  26. }
  27. func prepareStaticOptions(options []StaticOptions) StaticOptions {
  28. var opt StaticOptions
  29. if len(options) > 0 {
  30. opt = options[0]
  31. }
  32. // Defaults
  33. if len(opt.IndexFile) == 0 {
  34. opt.IndexFile = "index.html"
  35. }
  36. // Normalize the prefix if provided
  37. if opt.Prefix != "" {
  38. // Ensure we have a leading '/'
  39. if opt.Prefix[0] != '/' {
  40. opt.Prefix = "/" + opt.Prefix
  41. }
  42. // Remove any trailing '/'
  43. opt.Prefix = strings.TrimRight(opt.Prefix, "/")
  44. }
  45. return opt
  46. }
  47. // Static returns a middleware handler that serves static files in the given directory.
  48. func Static(directory string, staticOpt ...StaticOptions) Handler {
  49. if !filepath.IsAbs(directory) {
  50. directory = filepath.Join(Root, directory)
  51. }
  52. dir := http.Dir(directory)
  53. opt := prepareStaticOptions(staticOpt)
  54. return func(res http.ResponseWriter, req *http.Request, log *log.Logger) {
  55. if req.Method != "GET" && req.Method != "HEAD" {
  56. return
  57. }
  58. if opt.Exclude != "" && strings.HasPrefix(req.URL.Path, opt.Exclude) {
  59. return
  60. }
  61. file := req.URL.Path
  62. // if we have a prefix, filter requests by stripping the prefix
  63. if opt.Prefix != "" {
  64. if !strings.HasPrefix(file, opt.Prefix) {
  65. return
  66. }
  67. file = file[len(opt.Prefix):]
  68. if file != "" && file[0] != '/' {
  69. return
  70. }
  71. }
  72. f, err := dir.Open(file)
  73. if err != nil {
  74. // try any fallback before giving up
  75. if opt.Fallback != "" {
  76. file = opt.Fallback // so that logging stays true
  77. f, err = dir.Open(opt.Fallback)
  78. }
  79. if err != nil {
  80. // discard the error?
  81. return
  82. }
  83. }
  84. defer f.Close()
  85. fi, err := f.Stat()
  86. if err != nil {
  87. return
  88. }
  89. // try to serve index file
  90. if fi.IsDir() {
  91. // redirect if missing trailing slash
  92. if !strings.HasSuffix(req.URL.Path, "/") {
  93. dest := url.URL{
  94. Path: req.URL.Path + "/",
  95. RawQuery: req.URL.RawQuery,
  96. Fragment: req.URL.Fragment,
  97. }
  98. http.Redirect(res, req, dest.String(), http.StatusFound)
  99. return
  100. }
  101. file = path.Join(file, opt.IndexFile)
  102. f, err = dir.Open(file)
  103. if err != nil {
  104. return
  105. }
  106. defer f.Close()
  107. fi, err = f.Stat()
  108. if err != nil || fi.IsDir() {
  109. return
  110. }
  111. }
  112. if !opt.SkipLogging {
  113. log.Println("[Static] Serving " + file)
  114. }
  115. // Add an Expires header to the static content
  116. if opt.Expires != nil {
  117. res.Header().Set("Expires", opt.Expires())
  118. }
  119. http.ServeContent(res, req, file, fi.ModTime(), f)
  120. }
  121. }