static.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package static
  2. import (
  3. "net/http"
  4. "os"
  5. )
  6. type Static struct {
  7. dirIndexFile string
  8. }
  9. func New(file string) *Static {
  10. r := Static{dirIndexFile: file}
  11. return &r
  12. }
  13. func (this *Static) Response(dir string, w http.ResponseWriter, r *http.Request, before func(w http.ResponseWriter, r *http.Request), after func(w http.ResponseWriter, r *http.Request)) bool {
  14. if r.URL.Path == "/" {
  15. f, err := os.Open(dir + string(os.PathSeparator) + this.dirIndexFile)
  16. if err == nil {
  17. defer f.Close()
  18. st, err := os.Stat(dir + string(os.PathSeparator) + this.dirIndexFile)
  19. if err != nil {
  20. return false
  21. }
  22. if st.Mode().IsDir() {
  23. return false
  24. }
  25. if before != nil {
  26. before(w, r)
  27. }
  28. http.ServeFile(w, r, dir+string(os.PathSeparator)+this.dirIndexFile)
  29. if after != nil {
  30. after(w, r)
  31. }
  32. return true
  33. }
  34. } else {
  35. f, err := os.Open(dir + r.URL.Path)
  36. if err == nil {
  37. defer f.Close()
  38. st, err := os.Stat(dir + r.URL.Path)
  39. if err != nil {
  40. return false
  41. }
  42. if st.Mode().IsDir() {
  43. if r.URL.Path[len(r.URL.Path)-1] == '/' {
  44. fi, err := os.Open(dir + r.URL.Path + string(os.PathSeparator) + this.dirIndexFile)
  45. if err == nil {
  46. defer fi.Close()
  47. sti, err := os.Stat(dir + r.URL.Path + string(os.PathSeparator) + this.dirIndexFile)
  48. if err != nil {
  49. return false
  50. }
  51. if sti.Mode().IsDir() {
  52. return false
  53. }
  54. if before != nil {
  55. before(w, r)
  56. }
  57. http.ServeFile(w, r, dir+r.URL.Path+string(os.PathSeparator)+this.dirIndexFile)
  58. if after != nil {
  59. after(w, r)
  60. }
  61. return true
  62. }
  63. }
  64. return false
  65. }
  66. if before != nil {
  67. before(w, r)
  68. }
  69. http.ServeFile(w, r, dir+r.URL.Path)
  70. if after != nil {
  71. after(w, r)
  72. }
  73. return true
  74. }
  75. }
  76. return false
  77. }