Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package middleware
  2. import (
  3. "net/http"
  4. "path"
  5. "strings"
  6. "github.com/Sirupsen/logrus"
  7. )
  8. // Static serves as file server for static assets,
  9. // as convention, the given dir name will be used as the URL prefix.
  10. func Static(dir string) func(http.Handler) http.Handler {
  11. var (
  12. fs = http.Dir(dir)
  13. prefix = path.Join("/", dir)
  14. )
  15. return func(next http.Handler) http.Handler {
  16. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  17. // Accepts http GET | HEAD Only, ignores all requests not started with prefix.
  18. if r.Method != "GET" && r.Method != "HEAD" {
  19. next.ServeHTTP(w, r)
  20. return
  21. } else if !strings.HasPrefix(r.URL.Path, prefix) {
  22. next.ServeHTTP(w, r)
  23. return
  24. }
  25. filename := strings.TrimPrefix(r.URL.Path, prefix)
  26. if filename != "" && filename[0] != '/' {
  27. next.ServeHTTP(w, r)
  28. return
  29. }
  30. file, err := fs.Open(filename)
  31. if err != nil {
  32. next.ServeHTTP(w, r)
  33. return
  34. }
  35. defer file.Close()
  36. stat, err := file.Stat()
  37. if err != nil {
  38. next.ServeHTTP(w, r)
  39. return
  40. }
  41. // try to serve index filename
  42. if stat.IsDir() {
  43. // redirect if missing trailing slash
  44. if !strings.HasSuffix(r.URL.Path, "/") {
  45. http.Redirect(w, r, r.URL.Path+"/", http.StatusFound)
  46. return
  47. }
  48. filename = path.Join(filename, "index.html")
  49. file, err = fs.Open(filename)
  50. if err != nil {
  51. next.ServeHTTP(w, r)
  52. return
  53. }
  54. defer file.Close()
  55. stat, err = file.Stat()
  56. if err != nil || stat.IsDir() {
  57. next.ServeHTTP(w, r)
  58. return
  59. }
  60. }
  61. http.ServeContent(w, r, filename, stat.ModTime(), file)
  62. var header = w.Header()
  63. for key, values := range header {
  64. logrus.Infof("%s: %v", key, values)
  65. }
  66. })
  67. }
  68. }